device_watcher/
lib.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
360
361
// Copyright 2021 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 anyhow::{format_err, Context, Result};
use fidl_fuchsia_device::ControllerMarker;
use fidl_fuchsia_io as fio;
use fuchsia_fs::directory::{WatchEvent, Watcher};
use futures::stream::{Stream, StreamExt as _, TryStreamExt as _};
use std::path::PathBuf;

// Device metadata.
pub struct DeviceInfo<'a> {
    // The device's file name within the directory in which it was found.
    pub filename: &'a str,
    // The device's topological path.
    pub topological_path: String,
}

/// Watches the directory for a device for which the predicate returns `Some(t)`
/// and returns `t`.
pub async fn wait_for_device_with<T>(
    dev_dir: &fio::DirectoryProxy,
    predicate: impl Fn(DeviceInfo<'_>) -> Option<T>,
) -> Result<T, anyhow::Error> {
    let stream = watch_for_files(dev_dir).await?;
    let stream = stream.try_filter_map(|filename| {
        let predicate = &predicate;
        async move {
            let filename =
                filename.to_str().ok_or_else(|| format_err!("to_str for filename failed"))?;
            let controller_filename = filename.to_owned() + "/device_controller";

            let (controller_proxy, server_end) =
                fidl::endpoints::create_proxy::<ControllerMarker>();
            if dev_dir
                .open3(
                    &controller_filename,
                    fio::Flags::PROTOCOL_SERVICE,
                    &fio::Options::default(),
                    server_end.into_channel(),
                )
                .is_err()
            {
                return Ok(None);
            }

            let topological_path = controller_proxy.get_topological_path().await;
            let topological_path = match topological_path {
                Ok(topological_path) => topological_path,
                // Special case PEER_CLOSED; the peer is expected to close the
                // connection if it doesn't implement the controller protocol.
                Err(err) => match err {
                    fidl::Error::ClientChannelClosed { .. } => return Ok(None),
                    err => {
                        return Err(err).with_context(|| {
                            format!("failed to send get_topological_path on \"{}\"", filename)
                        })
                    }
                },
            };
            let topological_path = topological_path
                .map_err(zx_status::Status::from_raw)
                .with_context(|| format!("failed to get topological path on \"{}\"", filename))?;

            Ok(predicate(DeviceInfo { filename, topological_path }))
        }
    });
    futures::pin_mut!(stream);
    let item = stream.try_next().await?;
    item.ok_or_else(|| format_err!("stream ended prematurely"))
}

/// Returns a stream that contains the paths of any existing files and
/// directories in `dir` and any new files or directories created after this
/// function was invoked. These paths are relative to `dir`.
pub async fn watch_for_files(
    dir: &fio::DirectoryProxy,
) -> Result<impl Stream<Item = Result<PathBuf>>> {
    let watcher = Watcher::new(dir).await.context("failed to create watcher")?;
    Ok(watcher.map(|result| result.context("failed to get watcher event")).try_filter_map(|msg| {
        futures::future::ok(match msg.event {
            WatchEvent::EXISTING | WatchEvent::ADD_FILE => {
                if msg.filename == std::path::Path::new(".") {
                    None
                } else {
                    Some(msg.filename)
                }
            }
            _ => None,
        })
    }))
}

async fn wait_for_file(dir: &fio::DirectoryProxy, name: &str) -> Result<()> {
    let mut watcher = fuchsia_fs::directory::Watcher::new(dir).await?;
    while let Some(msg) = watcher.try_next().await? {
        if msg.event != fuchsia_fs::directory::WatchEvent::EXISTING
            && msg.event != fuchsia_fs::directory::WatchEvent::ADD_FILE
        {
            continue;
        }
        if msg.filename.to_str().unwrap() == name {
            return Ok(());
        }
    }
    unreachable!();
}

/// Open the path `name` within `dir`. This function waits for each directory to
/// be available before it opens it. If the path never appears this function
/// will wait forever.
async fn recursive_wait_and_open_with_flags<T, F>(
    mut dir: fio::DirectoryProxy,
    name: &str,
    flags: fio::Flags,
    op: F,
) -> Result<T>
where
    F: FnOnce(&fio::DirectoryProxy, &str, fio::Flags) -> T,
{
    let path = std::path::Path::new(name);
    let mut components = path.components().peekable();
    loop {
        let component =
            components.next().ok_or_else(|| format_err!("cannot wait for empty path"))?;
        let file = match component {
            std::path::Component::Normal(file) => file,
            // Per fuchsia.io/Directory.Open[0]:
            //
            // A leading '/' is allowed (and is treated the same way as if not present, i.e.
            // "/foo/bar' and "foo/bar" are the same).
            //
            // [0] https://cs.opensource.google/fuchsia/fuchsia/+/main:sdk/fidl/fuchsia.io/directory.fidl;l=211-237;drc=02426e16b637b25a21b1e53f9861855d476aaf49
            std::path::Component::RootDir => continue,
            component => {
                return Err(format_err!("path contains non-normal component {:?}", component))
            }
        };
        let file = file.to_str().unwrap();
        let () = wait_for_file(&dir, file).await?;
        if components.peek().is_some() {
            dir = fuchsia_fs::directory::open_directory_async(&dir, file, flags)?;
        } else {
            break Ok(op(&dir, file, flags));
        }
    }
}

/// Wait for `name` to be available in `dir`. This function waits for each directory along
/// the path and returns once it has waited on the final component in the path. If the path
/// never appears this function will wait forever.
pub async fn recursive_wait(dir: &fio::DirectoryProxy, name: &str) -> Result<()> {
    recursive_wait_and_open_with_flags(Clone::clone(dir), name, fio::Flags::empty(), |_, _, _| ())
        .await
}

/// Open the path `name` within `dir`. This function waits for each directory to
/// be available before it opens it. If the path never appears this function
/// will wait forever.
pub async fn recursive_wait_and_open_directory(
    dir: &fio::DirectoryProxy,
    name: &str,
) -> Result<fio::DirectoryProxy> {
    recursive_wait_and_open_with_flags(
        Clone::clone(dir),
        name,
        fio::Flags::PROTOCOL_DIRECTORY,
        fuchsia_fs::directory::open_async::<fio::DirectoryMarker>,
    )
    .await
    .and_then(|res| res.map_err(Into::into))
}

/// Connect to an instance of FIDL protocol hosted at `name` within `dir`. This function waits for
/// each directory to be available before it opens it. If the path never appears this function will
/// wait forever.
pub async fn recursive_wait_and_open<P: fidl::endpoints::ProtocolMarker>(
    dir: &fio::DirectoryProxy,
    name: &str,
) -> Result<P::Proxy> {
    recursive_wait_and_open_with_flags(
        Clone::clone(dir),
        name,
        fio::Flags::empty(),
        |dir, path, _flags| {
            // Cannot open services with other flags.
            fuchsia_fs::directory::open_async::<P>(dir, path, fio::Flags::PROTOCOL_SERVICE)
        },
    )
    .await
    .and_then(|res| res.map_err(Into::into))
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures::StreamExt;
    use std::collections::HashSet;
    use std::str::FromStr;
    use std::sync::Arc;
    use vfs::directory::entry_container::Directory;
    use vfs::execution_scope::ExecutionScope;
    use vfs::file::vmo::read_only;
    use {fidl_fuchsia_device as fdev, fuchsia_async as fasync};

    fn create_controller_service(topo_path: &'static str) -> Arc<vfs::service::Service> {
        vfs::service::host(move |mut stream: fdev::ControllerRequestStream| async move {
            match stream.try_next().await.unwrap() {
                Some(fdev::ControllerRequest::GetTopologicalPath { responder }) => {
                    let _ = responder.send(Ok(topo_path));
                }
                e => panic!("Unexpected request: {:?}", e),
            }
        })
    }

    #[fasync::run_singlethreaded(test)]
    async fn wait_for_device_by_topological_path() {
        let dir = vfs::pseudo_directory! {
          "a" => vfs::pseudo_directory! {
            "device_controller" => create_controller_service("/dev/test2/a/dev"),
          },
          "1" => vfs::pseudo_directory! {
            "device_controller" => create_controller_service("/dev/test2/1/dev"),
          },
          "x" => vfs::pseudo_directory! {
            "device_controller" => create_controller_service("/dev/test2/x/dev"),
          },
          "y" => vfs::pseudo_directory! {
            "device_controller" => create_controller_service("/dev/test2/y/dev"),
          },
        };

        let (dir_proxy, remote) = fidl::endpoints::create_proxy::<fio::DirectoryMarker>();
        let scope = ExecutionScope::new();
        let flags: fio::Flags = fio::Flags::PROTOCOL_DIRECTORY | fio::PERM_READABLE;
        let object_request =
            vfs::ObjectRequest::new3(flags, &Default::default(), remote.into_channel());
        object_request.handle(|object_request| {
            dir.open3(scope, vfs::path::Path::dot(), flags, object_request)
        });

        let path = wait_for_device_with(&dir_proxy, |DeviceInfo { filename, topological_path }| {
            (topological_path == "/dev/test2/x/dev").then(|| filename.to_string())
        })
        .await
        .unwrap();
        assert_eq!("x", path);
    }

    #[fasync::run_singlethreaded(test)]
    async fn watch_for_two_files() {
        let dir = vfs::pseudo_directory! {
          "a" => read_only(b"/a"),
          "b" => read_only(b"/b"),
        };

        let (dir_proxy, remote) = fidl::endpoints::create_proxy::<fio::DirectoryMarker>();
        let scope = ExecutionScope::new();
        let flags: fio::Flags = fio::Flags::PROTOCOL_DIRECTORY | fio::PERM_READABLE;
        let object_request =
            vfs::ObjectRequest::new3(flags, &Default::default(), remote.into_channel());
        object_request.handle(|object_request| {
            dir.open3(scope, vfs::path::Path::dot(), flags, object_request)
        });

        let stream = watch_for_files(&dir_proxy).await.unwrap();
        futures::pin_mut!(stream);
        let actual: HashSet<PathBuf> =
            vec![stream.next().await.unwrap().unwrap(), stream.next().await.unwrap().unwrap()]
                .into_iter()
                .collect();
        let expected: HashSet<PathBuf> =
            vec![PathBuf::from_str("a").unwrap(), PathBuf::from_str("b").unwrap()]
                .into_iter()
                .collect();
        assert_eq!(actual, expected);
    }

    #[fasync::run_singlethreaded(test)]
    async fn wait_for_device_topo_path_allows_files_and_dirs() {
        let dir = vfs::pseudo_directory! {
          "1" => vfs::pseudo_directory! {
            "test" => read_only("test file 1"),
            "test2" => read_only("test file 2"),
          },
          "2" => read_only("file 2"),
          "x" => vfs::pseudo_directory! {
            "device_controller" => create_controller_service("/dev/test2/x/dev"),
          },
          "3" => read_only("file 3"),
        };

        let (dir_proxy, remote) = fidl::endpoints::create_proxy::<fio::DirectoryMarker>();
        let scope = ExecutionScope::new();
        let flags: fio::Flags = fio::Flags::PROTOCOL_DIRECTORY | fio::PERM_READABLE;
        let object_request =
            vfs::ObjectRequest::new3(flags, &Default::default(), remote.into_channel());
        object_request.handle(|object_request| {
            dir.open3(scope, vfs::path::Path::dot(), flags, object_request)
        });

        let path = wait_for_device_with(&dir_proxy, |DeviceInfo { filename, topological_path }| {
            (topological_path == "/dev/test2/x/dev").then(|| filename.to_string())
        })
        .await
        .unwrap();
        assert_eq!("x", path);
    }

    #[fasync::run_singlethreaded(test)]
    async fn open_two_directories() {
        let (client, server) = fidl::endpoints::create_proxy::<fio::DirectoryMarker>();

        let root = vfs::pseudo_directory! {
            "test" => vfs::pseudo_directory! {
                "dir" => vfs::pseudo_directory! {},
            },
        };
        let flags: fio::Flags =
            fio::Flags::PROTOCOL_DIRECTORY | fio::PERM_READABLE | fio::Flags::PERM_EXECUTE;
        let object_request =
            vfs::ObjectRequest::new3(flags, &Default::default(), server.into_channel());
        object_request.handle(|object_request| {
            root.clone().open3(
                vfs::execution_scope::ExecutionScope::new(),
                vfs::path::Path::dot(),
                fio::Flags::PROTOCOL_DIRECTORY | fio::PERM_READABLE | fio::Flags::PERM_EXECUTE,
                object_request,
            )
        });

        let directory = recursive_wait_and_open_directory(&client, "test/dir").await.unwrap();
        let () = directory.close().await.unwrap().unwrap();
    }

    #[fasync::run_singlethreaded(test)]
    async fn open_directory_with_leading_slash() {
        let (client, server) = fidl::endpoints::create_proxy::<fio::DirectoryMarker>();

        let root = vfs::pseudo_directory! {
            "test" => vfs::pseudo_directory! {},
        };
        let flags: fio::Flags =
            fio::Flags::PROTOCOL_DIRECTORY | fio::PERM_READABLE | fio::Flags::PERM_EXECUTE;
        let object_request =
            vfs::ObjectRequest::new3(flags, &Default::default(), server.into_channel());
        object_request.handle(|object_request| {
            root.open3(
                vfs::execution_scope::ExecutionScope::new(),
                vfs::path::Path::dot(),
                flags,
                object_request,
            )
        });

        let directory = recursive_wait_and_open_directory(&client, "/test").await.unwrap();
        let () = directory.close().await.unwrap().unwrap();
    }
}