settings/factory_reset/
factory_reset_controller.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::base::{SettingInfo, SettingType};
use crate::call;
use crate::factory_reset::types::FactoryResetInfo;
use crate::handler::base::Request;
use crate::handler::setting_handler::controller::Handle;
use crate::handler::setting_handler::persist::{controller, ClientProxy};
use crate::handler::setting_handler::{
    ControllerError, ControllerStateResult, SettingHandlerResult, State,
};
use crate::service_context::ExternalServiceProxy;
use async_trait::async_trait;
use fidl_fuchsia_recovery_policy::{DeviceMarker, DeviceProxy};
use futures::lock::Mutex;
use settings_storage::device_storage::{DeviceStorage, DeviceStorageCompatible};
use settings_storage::storage_factory::{NoneT, StorageAccess};
use std::rc::Rc;

impl DeviceStorageCompatible for FactoryResetInfo {
    type Loader = NoneT;
    const KEY: &'static str = "factory_reset_info";
}

impl Default for FactoryResetInfo {
    fn default() -> Self {
        FactoryResetInfo::new(true)
    }
}

impl From<FactoryResetInfo> for SettingInfo {
    fn from(info: FactoryResetInfo) -> SettingInfo {
        SettingInfo::FactoryReset(info)
    }
}

type FactoryResetHandle = Rc<Mutex<FactoryResetManager>>;

/// Handles the mapping between [`Request`]s/[`State`] changes and the
/// [`FactoryResetManager`] logic. Wraps an Rc Mutex of the manager so that each field
/// doesn't need to be individually locked within the manager.
///
/// [`Request`]: crate::handler::base::Request
/// [`State`]: crate::handler::setting_handler::State
pub struct FactoryResetController {
    handle: FactoryResetHandle,
}

impl StorageAccess for FactoryResetController {
    type Storage = DeviceStorage;
    type Data = FactoryResetInfo;
    const STORAGE_KEY: &'static str = FactoryResetInfo::KEY;
}

/// Keeps track of the current state of factory reset, is responsible for persisting that state to
/// disk and notifying the fuchsia.recovery.policy.Device fidl interface of any changes.
pub struct FactoryResetManager {
    client: ClientProxy,
    is_local_reset_allowed: bool,
    factory_reset_policy_service: ExternalServiceProxy<DeviceProxy>,
}

impl FactoryResetManager {
    async fn from_client(client: ClientProxy) -> Result<FactoryResetHandle, ControllerError> {
        client
            .get_service_context()
            .connect::<DeviceMarker>()
            .await
            .map(|factory_reset_policy_service| {
                Rc::new(Mutex::new(Self {
                    client,
                    is_local_reset_allowed: true,
                    factory_reset_policy_service,
                }))
            })
            .map_err(|_| {
                ControllerError::InitFailure("could not connect to factory reset service".into())
            })
    }

    async fn restore(&mut self) -> SettingHandlerResult {
        self.restore_reset_state(true).await.map(|_| None)
    }

    async fn restore_reset_state(&mut self, send_event: bool) -> ControllerStateResult {
        let info = self.client.read_setting::<FactoryResetInfo>(fuchsia_trace::Id::new()).await;
        self.is_local_reset_allowed = info.is_local_reset_allowed;
        if send_event {
            call!(self.factory_reset_policy_service =>
                set_is_local_reset_allowed(info.is_local_reset_allowed)
            )
            .map_err(|e| {
                ControllerError::ExternalFailure(
                    SettingType::FactoryReset,
                    "factory_reset_policy".into(),
                    "restore_reset_state".into(),
                    format!("{e:?}").into(),
                )
            })?;
        }

        Ok(())
    }

    #[allow(clippy::result_large_err)] // TODO(https://fxbug.dev/42069089)
    fn get(&self) -> SettingHandlerResult {
        Ok(Some(FactoryResetInfo::new(self.is_local_reset_allowed).into()))
    }

    async fn set_local_reset_allowed(
        &mut self,
        is_local_reset_allowed: bool,
    ) -> SettingHandlerResult {
        let id = fuchsia_trace::Id::new();
        let mut info = self.client.read_setting::<FactoryResetInfo>(id).await;
        self.is_local_reset_allowed = is_local_reset_allowed;
        info.is_local_reset_allowed = is_local_reset_allowed;
        call!(self.factory_reset_policy_service =>
            set_is_local_reset_allowed(info.is_local_reset_allowed)
        )
        .map_err(|e| {
            ControllerError::ExternalFailure(
                SettingType::FactoryReset,
                "factory_reset_policy".into(),
                "set_local_reset_allowed".into(),
                format!("{e:?}").into(),
            )
        })?;
        self.client.write_setting(info.into(), id).await.map(|_| None)
    }
}

#[async_trait(?Send)]
impl controller::Create for FactoryResetController {
    async fn create(client: ClientProxy) -> Result<Self, ControllerError> {
        Ok(Self { handle: FactoryResetManager::from_client(client).await? })
    }
}

#[async_trait(?Send)]
impl Handle for FactoryResetController {
    async fn handle(&self, request: Request) -> Option<SettingHandlerResult> {
        match request {
            Request::Restore => Some(self.handle.lock().await.restore().await),
            Request::Get => Some(self.handle.lock().await.get()),
            Request::SetLocalResetAllowed(is_local_reset_allowed) => {
                Some(self.handle.lock().await.set_local_reset_allowed(is_local_reset_allowed).await)
            }
            _ => None,
        }
    }

    async fn change_state(&mut self, state: State) -> Option<ControllerStateResult> {
        match state {
            State::Startup => {
                // Restore the factory reset state locally but do not push to
                // the factory reset policy.
                Some(self.handle.lock().await.restore_reset_state(false).await)
            }
            _ => None,
        }
    }
}