Skip to main content

task/manager/
properties.rs

1// Properties module - handles task properties like user, group, and environment variables
2
3use super::*;
4use alloc::{string::String, vec::Vec};
5use users::{GroupIdentifier, UserIdentifier};
6
7/// Remove the variables called `name`. One non-generic copy serves set, remove and
8/// replace.
9fn remove_named(variables: &mut Vec<EnvironmentVariable>, name: &str) {
10    variables.retain(|variable| variable.get_name() != name);
11}
12
13impl Manager {
14    pub async fn set_user(
15        &self,
16        task_identifier: TaskIdentifier,
17        user: UserIdentifier,
18    ) -> Result<()> {
19        Self::get_task_mutable(&mut *self.0.write().await, task_identifier)?.user = user;
20
21        Ok(())
22    }
23
24    pub async fn set_group(
25        &self,
26        task_identifier: TaskIdentifier,
27        group: GroupIdentifier,
28    ) -> Result<()> {
29        Self::get_task_mutable(&mut *self.0.write().await, task_identifier)?.group = group;
30
31        Ok(())
32    }
33
34    /// Give `task_identifier` the identity `user` and `group` on behalf of the
35    /// program that launched it, instead of the one it inherited.
36    ///
37    /// The task, and every task it spawns from then on, is marked as running
38    /// with a granted identity (see [`Self::is_identity_granted`]). The mark is
39    /// set together with the identity, under one lock, and nothing clears it:
40    /// neither a later identity change nor the exit of an ancestor, so a
41    /// descendant keeps it even once it has been reparented to the root task.
42    ///
43    /// The mark holds against untrusted code, which cannot spawn tasks. Trusted
44    /// native code can still spawn a task with an unmarked parent of its choice,
45    /// just as it can change any task's identity.
46    pub async fn grant_identity(
47        &self,
48        task_identifier: TaskIdentifier,
49        user: UserIdentifier,
50        group: GroupIdentifier,
51    ) -> Result<()> {
52        let mut inner = self.0.write().await;
53        let metadata = Self::get_task_mutable(&mut inner, task_identifier)?;
54        metadata.user = user;
55        metadata.group = group;
56        metadata.identity_granted = true;
57
58        Ok(())
59    }
60
61    /// Whether `task_identifier`, or one of its ancestors, was given its
62    /// identity by its launcher through [`Self::grant_identity`]. Runtimes for
63    /// untrusted code use it to refuse running with an identity that another
64    /// program granted.
65    pub async fn is_identity_granted(&self, task_identifier: TaskIdentifier) -> Result<bool> {
66        Self::get_task(&*self.0.read().await, task_identifier).map(|task| task.identity_granted)
67    }
68
69    pub async fn set_environment_variable(
70        &self,
71        task_identifier: TaskIdentifier,
72        name: &str,
73        value: &str,
74    ) -> Result<()> {
75        let environment_variable = EnvironmentVariable::new(name, value);
76
77        // Keep the write lock for the entire operation
78        let mut inner = self.0.write().await;
79        let metadata = Self::get_task_mutable(&mut inner, task_identifier)?;
80
81        // A variable of the same name is replaced.
82        remove_named(&mut metadata.environment_variables, name);
83        metadata.environment_variables.push(environment_variable);
84
85        Ok(())
86    }
87
88    pub async fn set_environment_variables(
89        &self,
90        task_identifier: TaskIdentifier,
91        environment_variables: &[(&str, &str)],
92    ) -> Result<()> {
93        let mut inner = self.0.write().await;
94        let metadata = Self::get_task_mutable(&mut inner, task_identifier)?;
95
96        environment_variables.iter().for_each(|(name, value)| {
97            let environment_variable = EnvironmentVariable::new(name, value);
98            metadata.environment_variables.push(environment_variable);
99        });
100
101        Ok(())
102    }
103
104    /// Replace the whole environment of a task with `variables`, as one atomic
105    /// update. A later entry overrides an earlier one of the same name. A spawned
106    /// task starts with a copy of its parent's environment; this gives it an
107    /// explicit one instead.
108    pub async fn replace_environment_variables(
109        &self,
110        task_identifier: TaskIdentifier,
111        variables: Vec<EnvironmentVariable>,
112    ) -> Result<()> {
113        // Deduplicate before taking the lock, so the lock covers no allocation
114        // beyond the replaced list's release.
115        let mut replacement: Vec<EnvironmentVariable> = Vec::with_capacity(variables.len());
116        for variable in variables {
117            remove_named(&mut replacement, variable.get_name());
118            replacement.push(variable);
119        }
120        let mut inner = self.0.write().await;
121        Self::get_task_mutable(&mut inner, task_identifier)?.environment_variables = replacement;
122
123        Ok(())
124    }
125
126    /// Set the system value of the variable `name` to `value`.
127    ///
128    /// The root task gets `value`, and so does every task that still follows
129    /// the system value: a task whose `name` equals the root task's previous
130    /// value, or that has no `name` when the root task had none. A task that
131    /// set a value of its own keeps it. Tasks spawned later inherit `value`
132    /// from their parent, as every variable is inherited.
133    ///
134    /// All updated tasks share one string, and the update holds one lock, so
135    /// no task sees a mix of the old and the new value. A task that set its
136    /// own value equal to the previous system value cannot be told apart from
137    /// one that inherited it, so it follows the change too.
138    pub async fn set_system_environment_variable(&self, name: &str, value: &str) {
139        let variable = EnvironmentVariable::new(name, value);
140
141        let mut inner = self.0.write().await;
142        let previous = inner
143            .tasks
144            .get(&Self::ROOT_TASK_IDENTIFIER)
145            .and_then(|root| {
146                root.environment_variables
147                    .iter()
148                    .find(|variable| variable.get_name() == name)
149            })
150            .cloned();
151        let previous = previous.as_ref().map(EnvironmentVariable::get_value);
152
153        for (identifier, metadata) in inner.tasks.iter_mut() {
154            let current = metadata
155                .environment_variables
156                .iter()
157                .find(|variable| variable.get_name() == name)
158                .map(EnvironmentVariable::get_value);
159            if *identifier != Self::ROOT_TASK_IDENTIFIER && current != previous {
160                continue;
161            }
162            remove_named(&mut metadata.environment_variables, name);
163            metadata.environment_variables.push(variable.clone());
164        }
165    }
166
167    pub async fn remove_environment_variable(
168        &self,
169        task_identifier: TaskIdentifier,
170        name: &str,
171    ) -> Result<()> {
172        remove_named(
173            &mut Self::get_task_mutable(&mut *self.0.write().await, task_identifier)?
174                .environment_variables,
175            name,
176        );
177
178        Ok(())
179    }
180
181    /// Get user identifier of the owner of a task.
182    pub async fn get_user(&self, task_identifier: TaskIdentifier) -> Result<UserIdentifier> {
183        Self::get_task(&*self.0.read().await, task_identifier).map(|task| task.user)
184    }
185
186    /// Get group identifier of the owner of a task.
187    pub async fn get_group(&self, task_identifier: TaskIdentifier) -> Result<GroupIdentifier> {
188        Self::get_task(&*self.0.read().await, task_identifier).map(|task| task.group)
189    }
190
191    pub async fn get_environment_variable(
192        &self,
193        task_identifier: TaskIdentifier,
194        name: &str,
195    ) -> Result<EnvironmentVariable> {
196        Self::get_task(&*self.0.read().await, task_identifier)?
197            .environment_variables
198            .iter()
199            .find(|variable| variable.get_name() == name)
200            .cloned()
201            // If the variable is not found, return an error
202            .ok_or(Error::InvalidEnvironmentVariable)
203    }
204
205    /// Get one environment entry by its current index, sharing its string.
206    pub async fn get_environment_variable_at(
207        &self,
208        task_identifier: TaskIdentifier,
209        index: usize,
210    ) -> Result<Option<EnvironmentVariable>> {
211        Ok(Self::get_task(&*self.0.read().await, task_identifier)?
212            .environment_variables
213            .get(index)
214            .cloned())
215    }
216
217    pub async fn get_environment_variables(
218        &self,
219        task_identifier: TaskIdentifier,
220    ) -> Result<Vec<EnvironmentVariable>> {
221        Self::get_task(&*self.0.read().await, task_identifier)
222            .map(|task| task.environment_variables.clone())
223            .map_err(|_| Error::InvalidTaskIdentifier)
224    }
225
226    /// # Arguments
227    /// * `Task_identifier` - The identifier of the task.
228    pub async fn get_name(&self, task_identifier: TaskIdentifier) -> Result<String> {
229        Self::get_task(&*self.0.read().await, task_identifier).map(|task| task.name.clone())
230    }
231}