Home | History | Annotate | Download | only in update_manager
      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 <set>
     21 #include <string>
     22 
     23 #include <base/logging.h>
     24 #include <base/strings/string_util.h>
     25 #include <base/time/time.h>
     26 
     27 #include "update_engine/common/error_code.h"
     28 #include "update_engine/common/error_code_utils.h"
     29 #include "update_engine/common/utils.h"
     30 #include "update_engine/update_manager/device_policy_provider.h"
     31 #include "update_engine/update_manager/policy_utils.h"
     32 #include "update_engine/update_manager/shill_provider.h"
     33 
     34 using base::Time;
     35 using base::TimeDelta;
     36 using chromeos_update_engine::ErrorCode;
     37 using std::get;
     38 using std::max;
     39 using std::min;
     40 using std::set;
     41 using std::string;
     42 
     43 namespace {
     44 
     45 // Examines |err_code| and decides whether the URL index needs to be advanced,
     46 // the error count for the URL incremented, or none of the above. In the first
     47 // case, returns true; in the second case, increments |*url_num_error_p| and
     48 // returns false; otherwise just returns false.
     49 //
     50 // TODO(garnold) Adapted from PayloadState::UpdateFailed() (to be retired).
     51 bool HandleErrorCode(ErrorCode err_code, int* url_num_error_p) {
     52   err_code = chromeos_update_engine::utils::GetBaseErrorCode(err_code);
     53   switch (err_code) {
     54     // Errors which are good indicators of a problem with a particular URL or
     55     // the protocol used in the URL or entities in the communication channel
     56     // (e.g. proxies). We should try the next available URL in the next update
     57     // check to quickly recover from these errors.
     58     case ErrorCode::kPayloadHashMismatchError:
     59     case ErrorCode::kPayloadSizeMismatchError:
     60     case ErrorCode::kDownloadPayloadVerificationError:
     61     case ErrorCode::kDownloadPayloadPubKeyVerificationError:
     62     case ErrorCode::kSignedDeltaPayloadExpectedError:
     63     case ErrorCode::kDownloadInvalidMetadataMagicString:
     64     case ErrorCode::kDownloadSignatureMissingInManifest:
     65     case ErrorCode::kDownloadManifestParseError:
     66     case ErrorCode::kDownloadMetadataSignatureError:
     67     case ErrorCode::kDownloadMetadataSignatureVerificationError:
     68     case ErrorCode::kDownloadMetadataSignatureMismatch:
     69     case ErrorCode::kDownloadOperationHashVerificationError:
     70     case ErrorCode::kDownloadOperationExecutionError:
     71     case ErrorCode::kDownloadOperationHashMismatch:
     72     case ErrorCode::kDownloadInvalidMetadataSize:
     73     case ErrorCode::kDownloadInvalidMetadataSignature:
     74     case ErrorCode::kDownloadOperationHashMissingError:
     75     case ErrorCode::kDownloadMetadataSignatureMissingError:
     76     case ErrorCode::kPayloadMismatchedType:
     77     case ErrorCode::kUnsupportedMajorPayloadVersion:
     78     case ErrorCode::kUnsupportedMinorPayloadVersion:
     79       LOG(INFO) << "Advancing download URL due to error "
     80                 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
     81                 << " (" << static_cast<int>(err_code) << ")";
     82       return true;
     83 
     84     // Errors which seem to be just transient network/communication related
     85     // failures and do not indicate any inherent problem with the URL itself.
     86     // So, we should keep the current URL but just increment the
     87     // failure count to give it more chances. This way, while we maximize our
     88     // chances of downloading from the URLs that appear earlier in the response
     89     // (because download from a local server URL that appears earlier in a
     90     // response is preferable than downloading from the next URL which could be
     91     // an Internet URL and thus could be more expensive).
     92     case ErrorCode::kError:
     93     case ErrorCode::kDownloadTransferError:
     94     case ErrorCode::kDownloadWriteError:
     95     case ErrorCode::kDownloadStateInitializationError:
     96     case ErrorCode::kOmahaErrorInHTTPResponse:  // Aggregate for HTTP errors.
     97       LOG(INFO) << "Incrementing URL failure count due to error "
     98                 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
     99                 << " (" << static_cast<int>(err_code) << ")";
    100       *url_num_error_p += 1;
    101       return false;
    102 
    103     // Errors which are not specific to a URL and hence shouldn't result in
    104     // the URL being penalized. This can happen in two cases:
    105     // 1. We haven't started downloading anything: These errors don't cost us
    106     // anything in terms of actual payload bytes, so we should just do the
    107     // regular retries at the next update check.
    108     // 2. We have successfully downloaded the payload: In this case, the
    109     // payload attempt number would have been incremented and would take care
    110     // of the back-off at the next update check.
    111     // In either case, there's no need to update URL index or failure count.
    112     case ErrorCode::kOmahaRequestError:
    113     case ErrorCode::kOmahaResponseHandlerError:
    114     case ErrorCode::kPostinstallRunnerError:
    115     case ErrorCode::kFilesystemCopierError:
    116     case ErrorCode::kInstallDeviceOpenError:
    117     case ErrorCode::kKernelDeviceOpenError:
    118     case ErrorCode::kDownloadNewPartitionInfoError:
    119     case ErrorCode::kNewRootfsVerificationError:
    120     case ErrorCode::kNewKernelVerificationError:
    121     case ErrorCode::kPostinstallBootedFromFirmwareB:
    122     case ErrorCode::kPostinstallFirmwareRONotUpdatable:
    123     case ErrorCode::kOmahaRequestEmptyResponseError:
    124     case ErrorCode::kOmahaRequestXMLParseError:
    125     case ErrorCode::kOmahaResponseInvalid:
    126     case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
    127     case ErrorCode::kOmahaUpdateDeferredPerPolicy:
    128     case ErrorCode::kOmahaUpdateDeferredForBackoff:
    129     case ErrorCode::kPostinstallPowerwashError:
    130     case ErrorCode::kUpdateCanceledByChannelChange:
    131     case ErrorCode::kOmahaRequestXMLHasEntityDecl:
    132     case ErrorCode::kFilesystemVerifierError:
    133     case ErrorCode::kUserCanceled:
    134       LOG(INFO) << "Not changing URL index or failure count due to error "
    135                 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
    136                 << " (" << static_cast<int>(err_code) << ")";
    137       return false;
    138 
    139     case ErrorCode::kSuccess:                            // success code
    140     case ErrorCode::kUmaReportedMax:                     // not an error code
    141     case ErrorCode::kOmahaRequestHTTPResponseBase:       // aggregated already
    142     case ErrorCode::kDevModeFlag:                        // not an error code
    143     case ErrorCode::kResumedFlag:                        // not an error code
    144     case ErrorCode::kTestImageFlag:                      // not an error code
    145     case ErrorCode::kTestOmahaUrlFlag:                   // not an error code
    146     case ErrorCode::kSpecialFlags:                       // not an error code
    147       // These shouldn't happen. Enumerating these  explicitly here so that we
    148       // can let the compiler warn about new error codes that are added to
    149       // action_processor.h but not added here.
    150       LOG(WARNING) << "Unexpected error "
    151                    << chromeos_update_engine::utils::ErrorCodeToString(err_code)
    152                    << " (" << static_cast<int>(err_code) << ")";
    153     // Note: Not adding a default here so as to let the compiler warn us of
    154     // any new enums that were added in the .h but not listed in this switch.
    155   }
    156   return false;
    157 }
    158 
    159 // Checks whether |url| can be used under given download restrictions.
    160 bool IsUrlUsable(const string& url, bool http_allowed) {
    161   return http_allowed ||
    162          !base::StartsWith(url, "http://",
    163                            base::CompareCase::INSENSITIVE_ASCII);
    164 }
    165 
    166 }  // namespace
    167 
    168 namespace chromeos_update_manager {
    169 
    170 const int ChromeOSPolicy::kTimeoutInitialInterval =  7 * 60;
    171 
    172 // TODO(deymo): Split the update_manager policies for Brillo and ChromeOS and
    173 // make the update check periodic interval configurable.
    174 #ifdef __ANDROID__
    175 const int ChromeOSPolicy::kTimeoutPeriodicInterval = 5 * 60 * 60;
    176 const int ChromeOSPolicy::kTimeoutMaxBackoffInterval = 26 * 60 * 60;
    177 #else
    178 const int ChromeOSPolicy::kTimeoutPeriodicInterval = 45 * 60;
    179 const int ChromeOSPolicy::kTimeoutMaxBackoffInterval = 4 * 60 * 60;
    180 #endif  // __ANDROID__
    181 
    182 const int ChromeOSPolicy::kTimeoutRegularFuzz = 10 * 60;
    183 const int ChromeOSPolicy::kAttemptBackoffMaxIntervalInDays = 16;
    184 const int ChromeOSPolicy::kAttemptBackoffFuzzInHours = 12;
    185 const int ChromeOSPolicy::kMaxP2PAttempts = 10;
    186 const int ChromeOSPolicy::kMaxP2PAttemptsPeriodInSeconds = 5 * 24 * 60 * 60;
    187 
    188 EvalStatus ChromeOSPolicy::UpdateCheckAllowed(
    189     EvaluationContext* ec, State* state, string* error,
    190     UpdateCheckParams* result) const {
    191   // Set the default return values.
    192   result->updates_enabled = true;
    193   result->target_channel.clear();
    194   result->target_version_prefix.clear();
    195   result->is_interactive = false;
    196 
    197   DevicePolicyProvider* const dp_provider = state->device_policy_provider();
    198   UpdaterProvider* const updater_provider = state->updater_provider();
    199   SystemProvider* const system_provider = state->system_provider();
    200 
    201   // Do not perform any updates if booted from removable device. This decision
    202   // is final.
    203   const unsigned int* num_slots_p = ec->GetValue(
    204       system_provider->var_num_slots());
    205   if (!num_slots_p || *num_slots_p < 2) {
    206     LOG(INFO) << "Not enough slots for A/B updates, disabling update checks.";
    207     result->updates_enabled = false;
    208     return EvalStatus::kSucceeded;
    209   }
    210 
    211   const bool* device_policy_is_loaded_p = ec->GetValue(
    212       dp_provider->var_device_policy_is_loaded());
    213   if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
    214     // Check whether updates are disabled by policy.
    215     const bool* update_disabled_p = ec->GetValue(
    216         dp_provider->var_update_disabled());
    217     if (update_disabled_p && *update_disabled_p) {
    218       LOG(INFO) << "Updates disabled by policy, blocking update checks.";
    219       return EvalStatus::kAskMeAgainLater;
    220     }
    221 
    222     // Determine whether a target version prefix is dictated by policy.
    223     const string* target_version_prefix_p = ec->GetValue(
    224         dp_provider->var_target_version_prefix());
    225     if (target_version_prefix_p)
    226       result->target_version_prefix = *target_version_prefix_p;
    227 
    228     // Determine whether a target channel is dictated by policy.
    229     const bool* release_channel_delegated_p = ec->GetValue(
    230         dp_provider->var_release_channel_delegated());
    231     if (release_channel_delegated_p && !(*release_channel_delegated_p)) {
    232       const string* release_channel_p = ec->GetValue(
    233           dp_provider->var_release_channel());
    234       if (release_channel_p)
    235         result->target_channel = *release_channel_p;
    236     }
    237   }
    238 
    239   // First, check to see if an interactive update was requested.
    240   const UpdateRequestStatus* forced_update_requested_p = ec->GetValue(
    241       updater_provider->var_forced_update_requested());
    242   if (forced_update_requested_p &&
    243       *forced_update_requested_p != UpdateRequestStatus::kNone) {
    244     result->is_interactive =
    245         (*forced_update_requested_p == UpdateRequestStatus::kInteractive);
    246     LOG(INFO) << "Forced update signaled ("
    247               << (result->is_interactive ?  "interactive" : "periodic")
    248               << "), allowing update check.";
    249     return EvalStatus::kSucceeded;
    250   }
    251 
    252   // The logic thereafter applies to periodic updates. Bear in mind that we
    253   // should not return a final "no" if any of these criteria are not satisfied,
    254   // because the system may still update due to an interactive update request.
    255 
    256   // Unofficial builds should not perform periodic update checks.
    257   const bool* is_official_build_p = ec->GetValue(
    258       system_provider->var_is_official_build());
    259   if (is_official_build_p && !(*is_official_build_p)) {
    260     LOG(INFO) << "Unofficial build, blocking periodic update checks.";
    261     return EvalStatus::kAskMeAgainLater;
    262   }
    263 
    264   // If OOBE is enabled, wait until it is completed.
    265   const bool* is_oobe_enabled_p = ec->GetValue(
    266       state->config_provider()->var_is_oobe_enabled());
    267   if (is_oobe_enabled_p && *is_oobe_enabled_p) {
    268     const bool* is_oobe_complete_p = ec->GetValue(
    269         system_provider->var_is_oobe_complete());
    270     if (is_oobe_complete_p && !(*is_oobe_complete_p)) {
    271       LOG(INFO) << "OOBE not completed, blocking update checks.";
    272       return EvalStatus::kAskMeAgainLater;
    273     }
    274   }
    275 
    276   // Ensure that periodic update checks are timed properly.
    277   Time next_update_check;
    278   if (NextUpdateCheckTime(ec, state, error, &next_update_check) !=
    279       EvalStatus::kSucceeded) {
    280     return EvalStatus::kFailed;
    281   }
    282   if (!ec->IsWallclockTimeGreaterThan(next_update_check)) {
    283     LOG(INFO) << "Periodic check interval not satisfied, blocking until "
    284               << chromeos_update_engine::utils::ToString(next_update_check);
    285     return EvalStatus::kAskMeAgainLater;
    286   }
    287 
    288   // It is time to check for an update.
    289   LOG(INFO) << "Allowing update check.";
    290   return EvalStatus::kSucceeded;
    291 }
    292 
    293 EvalStatus ChromeOSPolicy::UpdateCanStart(
    294     EvaluationContext* ec,
    295     State* state,
    296     string* error,
    297     UpdateDownloadParams* result,
    298     const UpdateState update_state) const {
    299   // Set the default return values. Note that we set persisted values (backoff,
    300   // scattering) to the same values presented in the update state. The reason is
    301   // that preemptive returns, such as the case where an update check is due,
    302   // should not clear off the said values; rather, it is the deliberate
    303   // inference of new values that should cause them to be reset.
    304   result->update_can_start = false;
    305   result->cannot_start_reason = UpdateCannotStartReason::kUndefined;
    306   result->download_url_idx = -1;
    307   result->download_url_allowed = true;
    308   result->download_url_num_errors = 0;
    309   result->p2p_downloading_allowed = false;
    310   result->p2p_sharing_allowed = false;
    311   result->do_increment_failures = false;
    312   result->backoff_expiry = update_state.backoff_expiry;
    313   result->scatter_wait_period = update_state.scatter_wait_period;
    314   result->scatter_check_threshold = update_state.scatter_check_threshold;
    315 
    316   // Make sure that we're not due for an update check.
    317   UpdateCheckParams check_result;
    318   EvalStatus check_status = UpdateCheckAllowed(ec, state, error, &check_result);
    319   if (check_status == EvalStatus::kFailed)
    320     return EvalStatus::kFailed;
    321   bool is_check_due = (check_status == EvalStatus::kSucceeded &&
    322                        check_result.updates_enabled == true);
    323 
    324   // Check whether backoff applies, and if not then which URL can be used for
    325   // downloading. These require scanning the download error log, and so they are
    326   // done together.
    327   UpdateBackoffAndDownloadUrlResult backoff_url_result;
    328   EvalStatus backoff_url_status = UpdateBackoffAndDownloadUrl(
    329       ec, state, error, &backoff_url_result, update_state);
    330   if (backoff_url_status == EvalStatus::kFailed)
    331     return EvalStatus::kFailed;
    332   result->download_url_idx = backoff_url_result.url_idx;
    333   result->download_url_num_errors = backoff_url_result.url_num_errors;
    334   result->do_increment_failures = backoff_url_result.do_increment_failures;
    335   result->backoff_expiry = backoff_url_result.backoff_expiry;
    336   bool is_backoff_active =
    337       (backoff_url_status == EvalStatus::kAskMeAgainLater) ||
    338       !backoff_url_result.backoff_expiry.is_null();
    339 
    340   DevicePolicyProvider* const dp_provider = state->device_policy_provider();
    341   bool is_scattering_active = false;
    342   EvalStatus scattering_status = EvalStatus::kSucceeded;
    343 
    344   const bool* device_policy_is_loaded_p = ec->GetValue(
    345       dp_provider->var_device_policy_is_loaded());
    346   if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
    347     // Check whether scattering applies to this update attempt. We should not be
    348     // scattering if this is an interactive update check, or if OOBE is enabled
    349     // but not completed.
    350     //
    351     // Note: current code further suppresses scattering if a "deadline"
    352     // attribute is found in the Omaha response. However, it appears that the
    353     // presence of this attribute is merely indicative of an OOBE update, during
    354     // which we suppress scattering anyway.
    355     bool is_scattering_applicable = false;
    356     result->scatter_wait_period = kZeroInterval;
    357     result->scatter_check_threshold = 0;
    358     if (!update_state.is_interactive) {
    359       const bool* is_oobe_enabled_p = ec->GetValue(
    360           state->config_provider()->var_is_oobe_enabled());
    361       if (is_oobe_enabled_p && !(*is_oobe_enabled_p)) {
    362         is_scattering_applicable = true;
    363       } else {
    364         const bool* is_oobe_complete_p = ec->GetValue(
    365             state->system_provider()->var_is_oobe_complete());
    366         is_scattering_applicable = (is_oobe_complete_p && *is_oobe_complete_p);
    367       }
    368     }
    369 
    370     // Compute scattering values.
    371     if (is_scattering_applicable) {
    372       UpdateScatteringResult scatter_result;
    373       scattering_status = UpdateScattering(ec, state, error, &scatter_result,
    374                                            update_state);
    375       if (scattering_status == EvalStatus::kFailed) {
    376         return EvalStatus::kFailed;
    377       } else {
    378         result->scatter_wait_period = scatter_result.wait_period;
    379         result->scatter_check_threshold = scatter_result.check_threshold;
    380         if (scattering_status == EvalStatus::kAskMeAgainLater ||
    381             scatter_result.is_scattering)
    382           is_scattering_active = true;
    383       }
    384     }
    385   }
    386 
    387   // Find out whether P2P is globally enabled.
    388   bool p2p_enabled;
    389   EvalStatus p2p_enabled_status = P2PEnabled(ec, state, error, &p2p_enabled);
    390   if (p2p_enabled_status != EvalStatus::kSucceeded)
    391     return EvalStatus::kFailed;
    392 
    393   // Is P2P is enabled, consider allowing it for downloading and/or sharing.
    394   if (p2p_enabled) {
    395     // Sharing via P2P is allowed if not disabled by Omaha.
    396     if (update_state.p2p_sharing_disabled) {
    397       LOG(INFO) << "Blocked P2P sharing because it is disabled by Omaha.";
    398     } else {
    399       result->p2p_sharing_allowed = true;
    400     }
    401 
    402     // Downloading via P2P is allowed if not disabled by Omaha, an update is not
    403     // interactive, and other limits haven't been reached.
    404     if (update_state.p2p_downloading_disabled) {
    405       LOG(INFO) << "Blocked P2P downloading because it is disabled by Omaha.";
    406     } else if (update_state.is_interactive) {
    407       LOG(INFO) << "Blocked P2P downloading because update is interactive.";
    408     } else if (update_state.p2p_num_attempts >= kMaxP2PAttempts) {
    409       LOG(INFO) << "Blocked P2P downloading as it was attempted too many "
    410                    "times.";
    411     } else if (!update_state.p2p_first_attempted.is_null() &&
    412                ec->IsWallclockTimeGreaterThan(
    413                    update_state.p2p_first_attempted +
    414                    TimeDelta::FromSeconds(kMaxP2PAttemptsPeriodInSeconds))) {
    415       LOG(INFO) << "Blocked P2P downloading as its usage timespan exceeds "
    416                    "limit.";
    417     } else {
    418       // P2P download is allowed; if backoff or scattering are active, be sure
    419       // to suppress them, yet prevent any download URL from being used.
    420       result->p2p_downloading_allowed = true;
    421       if (is_backoff_active || is_scattering_active) {
    422         is_backoff_active = is_scattering_active = false;
    423         result->download_url_allowed = false;
    424       }
    425     }
    426   }
    427 
    428   // Check for various deterrents.
    429   if (is_check_due) {
    430     result->cannot_start_reason = UpdateCannotStartReason::kCheckDue;
    431     return EvalStatus::kSucceeded;
    432   }
    433   if (is_backoff_active) {
    434     result->cannot_start_reason = UpdateCannotStartReason::kBackoff;
    435     return backoff_url_status;
    436   }
    437   if (is_scattering_active) {
    438     result->cannot_start_reason = UpdateCannotStartReason::kScattering;
    439     return scattering_status;
    440   }
    441   if (result->download_url_idx < 0 && !result->p2p_downloading_allowed) {
    442     result->cannot_start_reason = UpdateCannotStartReason::kCannotDownload;
    443     return EvalStatus::kSucceeded;
    444   }
    445 
    446   // Update is good to go.
    447   result->update_can_start = true;
    448   return EvalStatus::kSucceeded;
    449 }
    450 
    451 // TODO(garnold) Logic in this method is based on
    452 // ConnectionManager::IsUpdateAllowedOver(); be sure to deprecate the latter.
    453 //
    454 // TODO(garnold) The current logic generally treats the list of allowed
    455 // connections coming from the device policy as a whitelist, meaning that it
    456 // can only be used for enabling connections, but not disable them. Further,
    457 // certain connection types (like Bluetooth) cannot be enabled even by policy.
    458 // In effect, the only thing that device policy can change is to enable
    459 // updates over a cellular network (disabled by default). We may want to
    460 // revisit this semantics, allowing greater flexibility in defining specific
    461 // permissions over all types of networks.
    462 EvalStatus ChromeOSPolicy::UpdateDownloadAllowed(
    463     EvaluationContext* ec,
    464     State* state,
    465     string* error,
    466     bool* result) const {
    467   // Get the current connection type.
    468   ShillProvider* const shill_provider = state->shill_provider();
    469   const ConnectionType* conn_type_p = ec->GetValue(
    470       shill_provider->var_conn_type());
    471   POLICY_CHECK_VALUE_AND_FAIL(conn_type_p, error);
    472   ConnectionType conn_type = *conn_type_p;
    473 
    474   // If we're tethering, treat it as a cellular connection.
    475   if (conn_type != ConnectionType::kCellular) {
    476     const ConnectionTethering* conn_tethering_p = ec->GetValue(
    477         shill_provider->var_conn_tethering());
    478     POLICY_CHECK_VALUE_AND_FAIL(conn_tethering_p, error);
    479     if (*conn_tethering_p == ConnectionTethering::kConfirmed)
    480       conn_type = ConnectionType::kCellular;
    481   }
    482 
    483   // By default, we allow updates for all connection types, with exceptions as
    484   // noted below. This also determines whether a device policy can override the
    485   // default.
    486   *result = true;
    487   bool device_policy_can_override = false;
    488   switch (conn_type) {
    489     case ConnectionType::kBluetooth:
    490       *result = false;
    491       break;
    492 
    493     case ConnectionType::kCellular:
    494       *result = false;
    495       device_policy_can_override = true;
    496       break;
    497 
    498     case ConnectionType::kUnknown:
    499       if (error)
    500         *error = "Unknown connection type";
    501       return EvalStatus::kFailed;
    502 
    503     default:
    504       break;  // Nothing to do.
    505   }
    506 
    507   // If update is allowed, we're done.
    508   if (*result)
    509     return EvalStatus::kSucceeded;
    510 
    511   // Check whether the device policy specifically allows this connection.
    512   if (device_policy_can_override) {
    513     DevicePolicyProvider* const dp_provider = state->device_policy_provider();
    514     const bool* device_policy_is_loaded_p = ec->GetValue(
    515         dp_provider->var_device_policy_is_loaded());
    516     if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
    517       const set<ConnectionType>* allowed_conn_types_p = ec->GetValue(
    518           dp_provider->var_allowed_connection_types_for_update());
    519       if (allowed_conn_types_p) {
    520         if (allowed_conn_types_p->count(conn_type)) {
    521           *result = true;
    522           return EvalStatus::kSucceeded;
    523         }
    524       } else if (conn_type == ConnectionType::kCellular) {
    525         // Local user settings can allow updates over cellular iff a policy was
    526         // loaded but no allowed connections were specified in it.
    527         const bool* update_over_cellular_allowed_p = ec->GetValue(
    528             state->updater_provider()->var_cellular_enabled());
    529         if (update_over_cellular_allowed_p && *update_over_cellular_allowed_p)
    530           *result = true;
    531       }
    532     }
    533   }
    534 
    535   return (*result ? EvalStatus::kSucceeded : EvalStatus::kAskMeAgainLater);
    536 }
    537 
    538 EvalStatus ChromeOSPolicy::P2PEnabled(EvaluationContext* ec,
    539                                       State* state,
    540                                       string* error,
    541                                       bool* result) const {
    542   bool enabled = false;
    543 
    544   // Determine whether use of P2P is allowed by policy. Even if P2P is not
    545   // explicitly allowed, we allow it if the device is enterprise enrolled (that
    546   // is, missing or empty owner string).
    547   DevicePolicyProvider* const dp_provider = state->device_policy_provider();
    548   const bool* device_policy_is_loaded_p = ec->GetValue(
    549       dp_provider->var_device_policy_is_loaded());
    550   if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
    551     const bool* policy_au_p2p_enabled_p = ec->GetValue(
    552         dp_provider->var_au_p2p_enabled());
    553     if (policy_au_p2p_enabled_p) {
    554       enabled = *policy_au_p2p_enabled_p;
    555     } else {
    556       const string* policy_owner_p = ec->GetValue(dp_provider->var_owner());
    557       if (!policy_owner_p || policy_owner_p->empty())
    558         enabled = true;
    559     }
    560   }
    561 
    562   // Enable P2P, if so mandated by the updater configuration. This is additive
    563   // to whether or not P2P is enabled by device policy.
    564   if (!enabled) {
    565     const bool* updater_p2p_enabled_p = ec->GetValue(
    566         state->updater_provider()->var_p2p_enabled());
    567     enabled = updater_p2p_enabled_p && *updater_p2p_enabled_p;
    568   }
    569 
    570   *result = enabled;
    571   return EvalStatus::kSucceeded;
    572 }
    573 
    574 EvalStatus ChromeOSPolicy::P2PEnabledChanged(EvaluationContext* ec,
    575                                              State* state,
    576                                              string* error,
    577                                              bool* result,
    578                                              bool prev_result) const {
    579   EvalStatus status = P2PEnabled(ec, state, error, result);
    580   if (status == EvalStatus::kSucceeded && *result == prev_result)
    581     return EvalStatus::kAskMeAgainLater;
    582   return status;
    583 }
    584 
    585 EvalStatus ChromeOSPolicy::NextUpdateCheckTime(EvaluationContext* ec,
    586                                                State* state, string* error,
    587                                                Time* next_update_check) const {
    588   UpdaterProvider* const updater_provider = state->updater_provider();
    589 
    590   // Don't check for updates too often. We limit the update checks to once every
    591   // some interval. The interval is kTimeoutInitialInterval the first time and
    592   // kTimeoutPeriodicInterval for the subsequent update checks. If the update
    593   // check fails, we increase the interval between the update checks
    594   // exponentially until kTimeoutMaxBackoffInterval. Finally, to avoid having
    595   // many chromebooks running update checks at the exact same time, we add some
    596   // fuzz to the interval.
    597   const Time* updater_started_time =
    598       ec->GetValue(updater_provider->var_updater_started_time());
    599   POLICY_CHECK_VALUE_AND_FAIL(updater_started_time, error);
    600 
    601   const Time* last_checked_time =
    602       ec->GetValue(updater_provider->var_last_checked_time());
    603 
    604   const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
    605   POLICY_CHECK_VALUE_AND_FAIL(seed, error);
    606 
    607   PRNG prng(*seed);
    608 
    609   // If this is the first attempt, compute and return an initial value.
    610   if (!last_checked_time || *last_checked_time < *updater_started_time) {
    611     *next_update_check = *updater_started_time + FuzzedInterval(
    612         &prng, kTimeoutInitialInterval, kTimeoutRegularFuzz);
    613     return EvalStatus::kSucceeded;
    614   }
    615 
    616   // Check whether the server is enforcing a poll interval; if not, this value
    617   // will be zero.
    618   const unsigned int* server_dictated_poll_interval = ec->GetValue(
    619       updater_provider->var_server_dictated_poll_interval());
    620   POLICY_CHECK_VALUE_AND_FAIL(server_dictated_poll_interval, error);
    621 
    622   int interval = *server_dictated_poll_interval;
    623   int fuzz = 0;
    624 
    625   // If no poll interval was dictated by server compute a back-off period,
    626   // starting from a predetermined base periodic interval and increasing
    627   // exponentially by the number of consecutive failed attempts.
    628   if (interval == 0) {
    629     const unsigned int* consecutive_failed_update_checks = ec->GetValue(
    630         updater_provider->var_consecutive_failed_update_checks());
    631     POLICY_CHECK_VALUE_AND_FAIL(consecutive_failed_update_checks, error);
    632 
    633     interval = kTimeoutPeriodicInterval;
    634     unsigned int num_failures = *consecutive_failed_update_checks;
    635     while (interval < kTimeoutMaxBackoffInterval && num_failures) {
    636       interval *= 2;
    637       num_failures--;
    638     }
    639   }
    640 
    641   // We cannot back off longer than the predetermined maximum interval.
    642   if (interval > kTimeoutMaxBackoffInterval)
    643     interval = kTimeoutMaxBackoffInterval;
    644 
    645   // We cannot back off shorter than the predetermined periodic interval. Also,
    646   // in this case set the fuzz to a predetermined regular value.
    647   if (interval <= kTimeoutPeriodicInterval) {
    648     interval = kTimeoutPeriodicInterval;
    649     fuzz = kTimeoutRegularFuzz;
    650   }
    651 
    652   // If not otherwise determined, defer to a fuzz of +/-(interval / 2).
    653   if (fuzz == 0)
    654     fuzz = interval;
    655 
    656   *next_update_check = *last_checked_time + FuzzedInterval(
    657       &prng, interval, fuzz);
    658   return EvalStatus::kSucceeded;
    659 }
    660 
    661 TimeDelta ChromeOSPolicy::FuzzedInterval(PRNG* prng, int interval, int fuzz) {
    662   DCHECK_GE(interval, 0);
    663   DCHECK_GE(fuzz, 0);
    664   int half_fuzz = fuzz / 2;
    665   // This guarantees the output interval is non negative.
    666   int interval_min = max(interval - half_fuzz, 0);
    667   int interval_max = interval + half_fuzz;
    668   return TimeDelta::FromSeconds(prng->RandMinMax(interval_min, interval_max));
    669 }
    670 
    671 EvalStatus ChromeOSPolicy::UpdateBackoffAndDownloadUrl(
    672     EvaluationContext* ec, State* state, string* error,
    673     UpdateBackoffAndDownloadUrlResult* result,
    674     const UpdateState& update_state) const {
    675   // Sanity checks.
    676   DCHECK_GE(update_state.download_errors_max, 0);
    677 
    678   // Set default result values.
    679   result->do_increment_failures = false;
    680   result->backoff_expiry = update_state.backoff_expiry;
    681   result->url_idx = -1;
    682   result->url_num_errors = 0;
    683 
    684   const bool* is_official_build_p = ec->GetValue(
    685       state->system_provider()->var_is_official_build());
    686   bool is_official_build = (is_official_build_p ? *is_official_build_p : true);
    687 
    688   // Check whether backoff is enabled.
    689   bool may_backoff = false;
    690   if (update_state.is_backoff_disabled) {
    691     LOG(INFO) << "Backoff disabled by Omaha.";
    692   } else if (update_state.is_interactive) {
    693     LOG(INFO) << "No backoff for interactive updates.";
    694   } else if (update_state.is_delta_payload) {
    695     LOG(INFO) << "No backoff for delta payloads.";
    696   } else if (!is_official_build) {
    697     LOG(INFO) << "No backoff for unofficial builds.";
    698   } else {
    699     may_backoff = true;
    700   }
    701 
    702   // If previous backoff still in effect, block.
    703   if (may_backoff && !update_state.backoff_expiry.is_null() &&
    704       !ec->IsWallclockTimeGreaterThan(update_state.backoff_expiry)) {
    705     LOG(INFO) << "Previous backoff has not expired, waiting.";
    706     return EvalStatus::kAskMeAgainLater;
    707   }
    708 
    709   // Determine whether HTTP downloads are forbidden by policy. This only
    710   // applies to official system builds; otherwise, HTTP is always enabled.
    711   bool http_allowed = true;
    712   if (is_official_build) {
    713     DevicePolicyProvider* const dp_provider = state->device_policy_provider();
    714     const bool* device_policy_is_loaded_p = ec->GetValue(
    715         dp_provider->var_device_policy_is_loaded());
    716     if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
    717       const bool* policy_http_downloads_enabled_p = ec->GetValue(
    718           dp_provider->var_http_downloads_enabled());
    719       http_allowed = (!policy_http_downloads_enabled_p ||
    720                       *policy_http_downloads_enabled_p);
    721     }
    722   }
    723 
    724   int url_idx = update_state.last_download_url_idx;
    725   if (url_idx < 0)
    726     url_idx = -1;
    727   bool do_advance_url = false;
    728   bool is_failure_occurred = false;
    729   Time err_time;
    730 
    731   // Scan the relevant part of the download error log, tracking which URLs are
    732   // being used, and accounting the number of errors for each URL. Note that
    733   // this process may not traverse all errors provided, as it may decide to bail
    734   // out midway depending on the particular errors exhibited, the number of
    735   // failures allowed, etc. When this ends, |url_idx| will point to the last URL
    736   // used (-1 if starting fresh), |do_advance_url| will determine whether the
    737   // URL needs to be advanced, and |err_time| the point in time when the last
    738   // reported error occurred.  Additionally, if the error log indicates that an
    739   // update attempt has failed (abnormal), then |is_failure_occurred| will be
    740   // set to true.
    741   const int num_urls = update_state.download_urls.size();
    742   int prev_url_idx = -1;
    743   int url_num_errors = update_state.last_download_url_num_errors;
    744   Time prev_err_time;
    745   bool is_first = true;
    746   for (const auto& err_tuple : update_state.download_errors) {
    747     // Do some sanity checks.
    748     int used_url_idx = get<0>(err_tuple);
    749     if (is_first && url_idx >= 0 && used_url_idx != url_idx) {
    750       LOG(WARNING) << "First URL in error log (" << used_url_idx
    751                    << ") not as expected (" << url_idx << ")";
    752     }
    753     is_first = false;
    754     url_idx = used_url_idx;
    755     if (url_idx < 0 || url_idx >= num_urls) {
    756       LOG(ERROR) << "Download error log contains an invalid URL index ("
    757                  << url_idx << ")";
    758       return EvalStatus::kFailed;
    759     }
    760     err_time = get<2>(err_tuple);
    761     if (!(prev_err_time.is_null() || err_time >= prev_err_time)) {
    762       // TODO(garnold) Monotonicity cannot really be assumed when dealing with
    763       // wallclock-based timestamps. However, we're making a simplifying
    764       // assumption so as to keep the policy implementation straightforward, for
    765       // now. In general, we should convert all timestamp handling in the
    766       // UpdateManager to use monotonic time (instead of wallclock), including
    767       // the computation of various expiration times (backoff, scattering, etc).
    768       // The client will do whatever conversions necessary when
    769       // persisting/retrieving these values across reboots. See chromium:408794.
    770       LOG(ERROR) << "Download error timestamps not monotonically increasing.";
    771       return EvalStatus::kFailed;
    772     }
    773     prev_err_time = err_time;
    774 
    775     // Ignore errors that happened before the last known failed attempt.
    776     if (!update_state.failures_last_updated.is_null() &&
    777         err_time <= update_state.failures_last_updated)
    778       continue;
    779 
    780     if (prev_url_idx >= 0) {
    781       if (url_idx < prev_url_idx) {
    782         LOG(ERROR) << "The URLs in the download error log have wrapped around ("
    783                    << prev_url_idx << "->" << url_idx
    784                    << "). This should not have happened and means that there's "
    785                       "a bug. To be conservative, we record a failed attempt "
    786                       "(invalidating the rest of the error log) and resume "
    787                       "download from the first usable URL.";
    788         url_idx = -1;
    789         is_failure_occurred = true;
    790         break;
    791       }
    792 
    793       if (url_idx > prev_url_idx) {
    794         url_num_errors = 0;
    795         do_advance_url = false;
    796       }
    797     }
    798 
    799     if (HandleErrorCode(get<1>(err_tuple), &url_num_errors) ||
    800         url_num_errors > update_state.download_errors_max)
    801       do_advance_url = true;
    802 
    803     prev_url_idx = url_idx;
    804   }
    805 
    806   // If required, advance to the next usable URL. If the URLs wraparound, we
    807   // mark an update attempt failure. Also be sure to set the download error
    808   // count to zero.
    809   if (url_idx < 0 || do_advance_url) {
    810     url_num_errors = 0;
    811     int start_url_idx = -1;
    812     do {
    813       if (++url_idx == num_urls) {
    814         url_idx = 0;
    815         // We only mark failure if an actual advancing of a URL was required.
    816         if (do_advance_url)
    817           is_failure_occurred = true;
    818       }
    819 
    820       if (start_url_idx < 0)
    821         start_url_idx = url_idx;
    822       else if (url_idx == start_url_idx)
    823         url_idx = -1;  // No usable URL.
    824     } while (url_idx >= 0 &&
    825              !IsUrlUsable(update_state.download_urls[url_idx], http_allowed));
    826   }
    827 
    828   // If we have a download URL but a failure was observed, compute a new backoff
    829   // expiry (if allowed). The backoff period is generally 2 ^ (num_failures - 1)
    830   // days, bounded by the size of int and kAttemptBackoffMaxIntervalInDays, and
    831   // fuzzed by kAttemptBackoffFuzzInHours hours. Backoff expiry is computed from
    832   // the latest recorded time of error.
    833   Time backoff_expiry;
    834   if (url_idx >= 0 && is_failure_occurred && may_backoff) {
    835     CHECK(!err_time.is_null())
    836         << "We must have an error timestamp if a failure occurred!";
    837     const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
    838     POLICY_CHECK_VALUE_AND_FAIL(seed, error);
    839     PRNG prng(*seed);
    840     int exp = min(update_state.num_failures,
    841                        static_cast<int>(sizeof(int)) * 8 - 2);
    842     TimeDelta backoff_interval = TimeDelta::FromDays(
    843         min(1 << exp, kAttemptBackoffMaxIntervalInDays));
    844     TimeDelta backoff_fuzz = TimeDelta::FromHours(kAttemptBackoffFuzzInHours);
    845     TimeDelta wait_period = FuzzedInterval(&prng, backoff_interval.InSeconds(),
    846                                            backoff_fuzz.InSeconds());
    847     backoff_expiry = err_time + wait_period;
    848 
    849     // If the newly computed backoff already expired, nullify it.
    850     if (ec->IsWallclockTimeGreaterThan(backoff_expiry))
    851       backoff_expiry = Time();
    852   }
    853 
    854   result->do_increment_failures = is_failure_occurred;
    855   result->backoff_expiry = backoff_expiry;
    856   result->url_idx = url_idx;
    857   result->url_num_errors = url_num_errors;
    858   return EvalStatus::kSucceeded;
    859 }
    860 
    861 EvalStatus ChromeOSPolicy::UpdateScattering(
    862     EvaluationContext* ec,
    863     State* state,
    864     string* error,
    865     UpdateScatteringResult* result,
    866     const UpdateState& update_state) const {
    867   // Preconditions. These stem from the postconditions and usage contract.
    868   DCHECK(update_state.scatter_wait_period >= kZeroInterval);
    869   DCHECK_GE(update_state.scatter_check_threshold, 0);
    870 
    871   // Set default result values.
    872   result->is_scattering = false;
    873   result->wait_period = kZeroInterval;
    874   result->check_threshold = 0;
    875 
    876   DevicePolicyProvider* const dp_provider = state->device_policy_provider();
    877 
    878   // Ensure that a device policy is loaded.
    879   const bool* device_policy_is_loaded_p = ec->GetValue(
    880       dp_provider->var_device_policy_is_loaded());
    881   if (!(device_policy_is_loaded_p && *device_policy_is_loaded_p))
    882     return EvalStatus::kSucceeded;
    883 
    884   // Is scattering enabled by policy?
    885   const TimeDelta* scatter_factor_p = ec->GetValue(
    886       dp_provider->var_scatter_factor());
    887   if (!scatter_factor_p || *scatter_factor_p == kZeroInterval)
    888     return EvalStatus::kSucceeded;
    889 
    890   // Obtain a pseudo-random number generator.
    891   const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
    892   POLICY_CHECK_VALUE_AND_FAIL(seed, error);
    893   PRNG prng(*seed);
    894 
    895   // Step 1: Maintain the scattering wait period.
    896   //
    897   // If no wait period was previously determined, or it no longer fits in the
    898   // scatter factor, then generate a new one. Otherwise, keep the one we have.
    899   TimeDelta wait_period = update_state.scatter_wait_period;
    900   if (wait_period == kZeroInterval || wait_period > *scatter_factor_p) {
    901     wait_period = TimeDelta::FromSeconds(
    902         prng.RandMinMax(1, scatter_factor_p->InSeconds()));
    903   }
    904 
    905   // If we surpassed the wait period or the max scatter period associated with
    906   // the update, then no wait is needed.
    907   Time wait_expires = (update_state.first_seen +
    908                        min(wait_period, update_state.scatter_wait_period_max));
    909   if (ec->IsWallclockTimeGreaterThan(wait_expires))
    910     wait_period = kZeroInterval;
    911 
    912   // Step 2: Maintain the update check threshold count.
    913   //
    914   // If an update check threshold is not specified then generate a new
    915   // one.
    916   int check_threshold = update_state.scatter_check_threshold;
    917   if (check_threshold == 0) {
    918     check_threshold = prng.RandMinMax(
    919         update_state.scatter_check_threshold_min,
    920         update_state.scatter_check_threshold_max);
    921   }
    922 
    923   // If the update check threshold is not within allowed range then nullify it.
    924   // TODO(garnold) This is compliant with current logic found in
    925   // OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied(). We may want
    926   // to change it so that it behaves similarly to the wait period case, namely
    927   // if the current value exceeds the maximum, we set a new one within range.
    928   if (check_threshold > update_state.scatter_check_threshold_max)
    929     check_threshold = 0;
    930 
    931   // If the update check threshold is non-zero and satisfied, then nullify it.
    932   if (check_threshold > 0 && update_state.num_checks >= check_threshold)
    933     check_threshold = 0;
    934 
    935   bool is_scattering = (wait_period != kZeroInterval || check_threshold);
    936   EvalStatus ret = EvalStatus::kSucceeded;
    937   if (is_scattering && wait_period == update_state.scatter_wait_period &&
    938       check_threshold == update_state.scatter_check_threshold)
    939     ret = EvalStatus::kAskMeAgainLater;
    940   result->is_scattering = is_scattering;
    941   result->wait_period = wait_period;
    942   result->check_threshold = check_threshold;
    943   return ret;
    944 }
    945 
    946 }  // namespace chromeos_update_manager
    947