chromeos_policy.cc 36 KB

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