vfs/
token_registry.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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
// Copyright 2019 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.

//! Implementation of [`TokenRegistry`].

use crate::directory::entry_container::MutableDirectory;
use fidl::{Event, Handle, HandleBased, Rights};
use pin_project::{pin_project, pinned_drop};
use std::collections::hash_map::{Entry, HashMap};
use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use zx_status::Status;

#[cfg(not(target_os = "fuchsia"))]
use fuchsia_async::emulated_handle::{AsHandleRef, Koid};
#[cfg(target_os = "fuchsia")]
use zx::{AsHandleRef, Koid};

const DEFAULT_TOKEN_RIGHTS: Rights = Rights::BASIC;

pub struct TokenRegistry {
    inner: Mutex<Inner>,
}

struct Inner {
    /// Maps an owner to a handle used as a token for the owner.  Handles do not change their koid
    /// value while they are alive.  We will use the koid of a handle we receive later from the user
    /// of the API to find the owner that has this particular handle associated with it.
    ///
    /// Every entry in owner_to_token will have a reverse mapping in token_to_owner.
    ///
    /// Owners must be wrapped in Tokenizable which will ensure tokens are unregistered when
    /// Tokenizable is dropped.  They must be pinned since pointers are used.  They must also
    /// implement the TokenInterface trait which extracts the information that `get_owner` returns.
    owner_to_token: HashMap<*const (), Handle>,

    /// Maps a koid of an owner to the owner.
    token_to_owner: HashMap<Koid, *const dyn TokenInterface>,
}

unsafe impl Send for Inner {}

impl TokenRegistry {
    pub fn new() -> Self {
        Self {
            inner: Mutex::new(Inner {
                owner_to_token: HashMap::new(),
                token_to_owner: HashMap::new(),
            }),
        }
    }

    /// Returns a token for the owner, creating one if one doesn't already exist.  Tokens will be
    /// automatically removed when Tokenizable is dropped.
    pub fn get_token<T: TokenInterface>(owner: Pin<&Tokenizable<T>>) -> Result<Handle, Status> {
        let ptr = owner.get_ref() as *const _ as *const ();
        let mut this = owner.token_registry().inner.lock().unwrap();
        let Inner { owner_to_token, token_to_owner, .. } = &mut *this;
        match owner_to_token.entry(ptr) {
            Entry::Occupied(o) => o.into_mut(),
            Entry::Vacant(v) => {
                let handle = Event::create().into_handle();
                let koid = handle.get_koid()?;
                assert!(
                    token_to_owner.insert(koid, &owner.0 as &dyn TokenInterface).is_none(),
                    "koid is a duplicate"
                );
                v.insert(handle)
            }
        }
        .duplicate_handle(DEFAULT_TOKEN_RIGHTS)
    }

    /// Returns the information provided by get_node_and_flags for the given token.  Returns None if
    /// no such token exists (perhaps because the owner has been dropped).
    pub fn get_owner(&self, token: Handle) -> Result<Option<Arc<dyn MutableDirectory>>, Status> {
        let koid = token.get_koid()?;
        let this = self.inner.lock().unwrap();

        match this.token_to_owner.get(&koid) {
            Some(owner) => {
                // SAFETY: This is safe because Tokenizable's drop will ensure that unregister is
                // called to avoid any dangling pointers.
                Ok(Some(unsafe { (**owner).get_node() }))
            }
            None => Ok(None),
        }
    }

    // Unregisters the token. This is done automatically by Tokenizable below.
    fn unregister<T: TokenInterface>(&self, owner: &Tokenizable<T>) {
        let ptr = owner as *const _ as *const ();
        let mut this = self.inner.lock().unwrap();

        if let Some(handle) = this.owner_to_token.remove(&ptr) {
            this.token_to_owner.remove(&handle.get_koid().unwrap()).unwrap();
        }
    }
}

pub trait TokenInterface: 'static {
    /// Returns the node and flags that correspond with this token.  This information is returned by
    /// the `get_owner` method.  For now this always returns Arc<dyn MutableDirectory> but it should
    /// be possible to change this so that files can be represented in future if and when the need
    /// arises.
    fn get_node(&self) -> Arc<dyn MutableDirectory>;

    /// Returns the token registry.
    fn token_registry(&self) -> &TokenRegistry;
}

/// Tokenizable is to be used to wrap anything that might need to have tokens generated.  It will
/// ensure that the token is unregistered when Tokenizable is dropped.
#[pin_project(!Unpin, PinnedDrop)]
pub struct Tokenizable<T: TokenInterface>(#[pin] T);

impl<T: TokenInterface> Tokenizable<T> {
    pub fn new(inner: T) -> Self {
        Self(inner)
    }

    pub fn as_mut(self: Pin<&mut Self>) -> Pin<&mut T> {
        self.project().0
    }
}

impl<T: TokenInterface> Deref for Tokenizable<T> {
    type Target = T;

    fn deref(&self) -> &T {
        &self.0
    }
}

impl<T: TokenInterface> DerefMut for Tokenizable<T> {
    fn deref_mut(&mut self) -> &mut T {
        &mut self.0
    }
}

#[pinned_drop]
impl<T: TokenInterface> PinnedDrop for Tokenizable<T> {
    fn drop(self: Pin<&mut Self>) {
        self.0.token_registry().unregister(&self);
    }
}

#[cfg(test)]
mod tests {
    use self::mocks::{MockChannel, MockDirectory};
    use super::{TokenRegistry, Tokenizable, DEFAULT_TOKEN_RIGHTS};
    use fidl::{AsHandleRef, HandleBased, Rights};
    use futures::pin_mut;
    use std::sync::Arc;

    #[test]
    fn client_register_same_token() {
        let registry = Arc::new(TokenRegistry::new());
        let client = Tokenizable(MockChannel(registry.clone(), MockDirectory::new()));
        pin_mut!(client);

        let token1 = TokenRegistry::get_token(client.as_ref()).unwrap();
        let token2 = TokenRegistry::get_token(client.as_ref()).unwrap();

        let koid1 = token1.get_koid().unwrap();
        let koid2 = token2.get_koid().unwrap();
        assert_eq!(koid1, koid2);
    }

    #[test]
    fn token_rights() {
        let registry = Arc::new(TokenRegistry::new());
        let client = Tokenizable(MockChannel(registry.clone(), MockDirectory::new()));
        pin_mut!(client);

        let token = TokenRegistry::get_token(client.as_ref()).unwrap();

        assert_eq!(token.basic_info().unwrap().rights, DEFAULT_TOKEN_RIGHTS);
    }

    #[test]
    fn client_unregister() {
        let registry = Arc::new(TokenRegistry::new());

        let token = {
            let client = Tokenizable(MockChannel(registry.clone(), MockDirectory::new()));
            pin_mut!(client);

            let token = TokenRegistry::get_token(client.as_ref()).unwrap();

            {
                let res = registry
                    .get_owner(token.duplicate_handle(Rights::SAME_RIGHTS).unwrap())
                    .unwrap()
                    .unwrap();
                // Note this ugly cast in place of `Arc::ptr_eq(&client, &res)` here is to ensure we
                // don't compare vtable pointers, which are not strictly guaranteed to be the same
                // across casts done in different code generation units at compilation time.
                assert_eq!(Arc::as_ptr(&client.1) as *const (), Arc::as_ptr(&res) as *const ());
            }

            token
        };

        assert!(
            registry
                .get_owner(token.duplicate_handle(Rights::SAME_RIGHTS).unwrap())
                .unwrap()
                .is_none(),
            "`registry.get_owner() is not `None` after an connection dropped."
        );
    }

    #[test]
    fn client_get_token_twice_unregister() {
        let registry = Arc::new(TokenRegistry::new());

        let token = {
            let client = Tokenizable(MockChannel(registry.clone(), MockDirectory::new()));
            pin_mut!(client);

            let token = TokenRegistry::get_token(client.as_ref()).unwrap();

            {
                let token2 = TokenRegistry::get_token(client.as_ref()).unwrap();

                let koid1 = token.get_koid().unwrap();
                let koid2 = token2.get_koid().unwrap();
                assert_eq!(koid1, koid2);
            }

            token
        };

        assert!(
            registry
                .get_owner(token.duplicate_handle(Rights::SAME_RIGHTS).unwrap())
                .unwrap()
                .is_none(),
            "`registry.get_owner() is not `None` after connection dropped."
        );
    }

    mod mocks {
        use crate::directory::dirents_sink;
        use crate::directory::entry::{EntryInfo, GetEntryInfo};
        use crate::directory::entry_container::{Directory, DirectoryWatcher, MutableDirectory};
        use crate::directory::traversal_position::TraversalPosition;
        use crate::execution_scope::ExecutionScope;
        use crate::node::Node;
        use crate::path::Path;
        use crate::token_registry::{TokenInterface, TokenRegistry};
        use crate::ObjectRequestRef;
        use fidl::endpoints::ServerEnd;
        use fidl_fuchsia_io as fio;
        use std::sync::Arc;
        use zx_status::Status;

        pub(super) struct MockChannel(pub Arc<TokenRegistry>, pub Arc<MockDirectory>);

        impl TokenInterface for MockChannel {
            fn get_node(&self) -> Arc<dyn MutableDirectory> {
                self.1.clone()
            }

            fn token_registry(&self) -> &TokenRegistry {
                &self.0
            }
        }

        pub(super) struct MockDirectory {}

        impl MockDirectory {
            pub(super) fn new() -> Arc<Self> {
                Arc::new(Self {})
            }
        }

        impl GetEntryInfo for MockDirectory {
            fn entry_info(&self) -> EntryInfo {
                EntryInfo::new(fio::INO_UNKNOWN, fio::DirentType::Directory)
            }
        }

        impl Node for MockDirectory {
            async fn get_attributes(
                &self,
                _query: fio::NodeAttributesQuery,
            ) -> Result<fio::NodeAttributes2, Status> {
                unimplemented!("Not implemented");
            }
        }

        impl Directory for MockDirectory {
            fn open(
                self: Arc<Self>,
                _scope: ExecutionScope,
                _flags: fio::OpenFlags,
                _path: Path,
                _server_end: ServerEnd<fio::NodeMarker>,
            ) {
            }

            fn open3(
                self: Arc<Self>,
                _scope: ExecutionScope,
                _path: Path,
                _flags: fio::Flags,
                _object_request: ObjectRequestRef<'_>,
            ) -> Result<(), Status> {
                unimplemented!("Not implemented");
            }

            async fn read_dirents<'a>(
                &'a self,
                _pos: &'a TraversalPosition,
                _sink: Box<dyn dirents_sink::Sink>,
            ) -> Result<(TraversalPosition, Box<dyn dirents_sink::Sealed>), Status> {
                unimplemented!("Not implemented!")
            }

            fn register_watcher(
                self: Arc<Self>,
                _scope: ExecutionScope,
                _mask: fio::WatchMask,
                _watcher: DirectoryWatcher,
            ) -> Result<(), Status> {
                unimplemented!("Not implemented!")
            }

            fn unregister_watcher(self: Arc<Self>, _key: usize) {
                unimplemented!("Not implemented!")
            }
        }

        impl MutableDirectory for MockDirectory {
            async fn unlink(
                self: Arc<Self>,
                _name: &str,
                _must_be_directory: bool,
            ) -> Result<(), Status> {
                unimplemented!("Not implemented!")
            }

            async fn update_attributes(
                &self,
                _attributes: fio::MutableNodeAttributes,
            ) -> Result<(), Status> {
                unimplemented!("Not implemented!")
            }

            async fn sync(&self) -> Result<(), Status> {
                unimplemented!("Not implemented!");
            }
        }
    }
}