component_debug/storage/
copy.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
// 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 crate::io::{Directory, LocalDirectory, RemoteDirectory};
use crate::path::{
    add_source_filename_to_path_if_absent, LocalOrRemoteComponentStoragePath,
    REMOTE_COMPONENT_STORAGE_PATH_HELP,
};
use anyhow::{anyhow, bail, Result};
use fidl::endpoints::create_proxy;
use fidl_fuchsia_io as fio;
use fidl_fuchsia_sys2::StorageAdminProxy;
use std::path::PathBuf;

/// Transfer a file between the host machine and the Fuchsia device.
/// Can be used to upload a file to or from the Fuchsia device.
///
/// # Arguments
/// * `storage_admin`: The StorageAdminProxy.
/// * `source_path`: The path to a file on the host machine to be uploaded to the device or to a file on the device to be downloaded on the host machine
/// * `destination_path`: The path and filename on the target component or the host machine where to save the file
pub async fn copy(
    storage_admin: StorageAdminProxy,
    source_path: String,
    destination_path: String,
) -> Result<()> {
    let (dir_proxy, server) = create_proxy::<fio::DirectoryMarker>();
    let server = server.into_channel();
    let storage_dir = RemoteDirectory::from_proxy(dir_proxy);

    match (
        LocalOrRemoteComponentStoragePath::parse(&source_path),
        LocalOrRemoteComponentStoragePath::parse(&destination_path),
    ) {
        (
            LocalOrRemoteComponentStoragePath::Remote(source),
            LocalOrRemoteComponentStoragePath::Local(destination_path),
        ) => {
            // Copying from remote to host
            storage_admin
                .open_component_storage_by_id(&source.instance_id, server.into())
                .await?
                .map_err(|e| anyhow!("Could not open component storage: {:?}", e))?;

            let destination_dir = LocalDirectory::new();
            do_copy(&storage_dir, &source.relative_path, &destination_dir, &destination_path).await
        }
        (
            LocalOrRemoteComponentStoragePath::Local(source_path),
            LocalOrRemoteComponentStoragePath::Remote(destination),
        ) => {
            // Copying from host to remote
            storage_admin
                .open_component_storage_by_id(&destination.instance_id, server.into())
                .await?
                .map_err(|e| anyhow!("Could not open component storage: {:?}", e))?;

            let source_dir = LocalDirectory::new();
            do_copy(&source_dir, &source_path, &storage_dir, &destination.relative_path).await
        }
        _ => {
            bail!(
                "One path must be remote and the other must be host. {}",
                REMOTE_COMPONENT_STORAGE_PATH_HELP
            )
        }
    }
}

async fn do_copy<S: Directory, D: Directory>(
    source_dir: &S,
    source_path: &PathBuf,
    destination_dir: &D,
    destination_path: &PathBuf,
) -> Result<()> {
    let destination_path_path =
        add_source_filename_to_path_if_absent(destination_dir, source_path, destination_path)
            .await?;

    let data = source_dir.read_file_bytes(source_path).await?;
    destination_dir.write_file(destination_path_path, &data).await
}

////////////////////////////////////////////////////////////////////////////////
// tests

#[cfg(test)]
mod test {
    use super::*;
    use crate::storage::test::{
        node_to_file, setup_fake_storage_admin, setup_fake_storage_admin_with_tmp,
    };
    use fidl_fuchsia_io as fio;
    use futures::TryStreamExt;
    use std::collections::HashMap;
    use std::fs::{read, write};
    use tempfile::tempdir;

    const EXPECTED_DATA: [u8; 4] = [0x0, 0x1, 0x2, 0x3];

    // TODO(xbhatnag): Replace this mock with something more robust like VFS.
    // Currently VFS is not cross-platform.
    fn setup_fake_directory(mut root_dir: fio::DirectoryRequestStream) {
        fuchsia_async::Task::local(async move {
            // Serve the root directory
            // Rewind on root directory should succeed
            let request = root_dir.try_next().await;
            if let Ok(Some(fio::DirectoryRequest::Open3 { path, flags, object, .. })) = request {
                if path == "from_local" {
                    assert!(flags.intersects(fio::Flags::FLAG_MAYBE_CREATE));
                    setup_fake_file_from_local(node_to_file(object.into()));
                } else if path == "from_device" {
                    setup_fake_file_from_device(node_to_file(object.into()));
                } else {
                    panic!("incorrect path: {}", path);
                }
            } else {
                panic!("did not get open request: {:?}", request)
            }
        })
        .detach();
    }

    fn setup_fake_file_from_local(mut file: fio::FileRequestStream) {
        fuchsia_async::Task::local(async move {
            // Serve the root directory
            // Truncating the file should succeed
            let request = file.try_next().await;
            if let Ok(Some(fio::FileRequest::Resize { length, responder })) = request {
                assert_eq!(length, 0);
                responder.send(Ok(())).unwrap();
            } else {
                panic!("did not get resize request: {:?}", request)
            }

            // Writing the file should succeed
            let request = file.try_next().await;
            if let Ok(Some(fio::FileRequest::Write { data, responder })) = request {
                assert_eq!(data, EXPECTED_DATA);
                responder.send(Ok(data.len() as u64)).unwrap();
            } else {
                panic!("did not get write request: {:?}", request)
            }

            // Closing file should succeed
            let request = file.try_next().await;
            if let Ok(Some(fio::FileRequest::Close { responder })) = request {
                responder.send(Ok(())).unwrap();
            } else {
                panic!("did not get close request: {:?}", request)
            }
        })
        .detach();
    }

    fn setup_fake_file_from_device(mut file: fio::FileRequestStream) {
        fuchsia_async::Task::local(async move {
            // Serve the root directory
            // Reading the file should succeed
            let request = file.try_next().await;
            if let Ok(Some(fio::FileRequest::Read { responder, .. })) = request {
                responder.send(Ok(&EXPECTED_DATA)).unwrap();
            } else {
                panic!("did not get read request: {:?}", request)
            }

            // Reading the file should not return any more data
            let request = file.try_next().await;
            if let Ok(Some(fio::FileRequest::Read { responder, .. })) = request {
                responder.send(Ok(&[])).unwrap();
            } else {
                panic!("did not get read request: {:?}", request)
            }

            // Closing file should succeed
            let request = file.try_next().await;
            if let Ok(Some(fio::FileRequest::Close { responder })) = request {
                responder.send(Ok(())).unwrap();
            } else {
                panic!("did not get close request: {:?}", request)
            }
        })
        .detach();
    }

    #[fuchsia::test]
    async fn test_copy_local_to_device() -> Result<()> {
        let dir = tempdir().unwrap();
        let storage_admin = setup_fake_storage_admin_with_tmp("123456", HashMap::new());
        let from_local_filepath = dir.path().join("from_local");
        write(&from_local_filepath, &EXPECTED_DATA).unwrap();
        copy(
            storage_admin,
            from_local_filepath.display().to_string(),
            "123456::from_local".to_string(),
        )
        .await
    }

    #[fuchsia::test]
    async fn test_copy_local_to_device_different_file_names() -> Result<()> {
        let dir = tempdir().unwrap();
        let storage_admin = setup_fake_storage_admin_with_tmp("123456", HashMap::new());
        let from_local_filepath = dir.path().join("from_local");
        write(&from_local_filepath, &EXPECTED_DATA).unwrap();
        copy(
            storage_admin,
            from_local_filepath.display().to_string(),
            "123456::from_local_test".to_string(),
        )
        .await
    }

    #[fuchsia::test]
    async fn test_copy_local_to_device_infer_path() -> Result<()> {
        let dir = tempdir().unwrap();
        let storage_admin = setup_fake_storage_admin_with_tmp("123456", HashMap::new());
        let from_local_filepath = dir.path().join("from_local");
        write(&from_local_filepath, &EXPECTED_DATA).unwrap();
        copy(storage_admin, from_local_filepath.display().to_string(), "123456::".to_string()).await
    }

    #[fuchsia::test]
    async fn test_copy_local_to_device_infer_slash_path() -> Result<()> {
        let dir = tempdir().unwrap();
        let storage_admin = setup_fake_storage_admin_with_tmp("123456", HashMap::new());
        let from_local_filepath = dir.path().join("from_local");
        write(&from_local_filepath, &EXPECTED_DATA).unwrap();
        copy(storage_admin, from_local_filepath.display().to_string(), "123456::/".to_string())
            .await
    }

    #[fuchsia::test]
    async fn test_copy_local_to_device_overwrite_file() -> Result<()> {
        let dir = tempdir().unwrap();
        let mut seed_files = HashMap::new();
        seed_files.insert("from_local", "Lorem Ipsum");
        let storage_admin = setup_fake_storage_admin_with_tmp("123456", seed_files);
        let from_local_filepath = dir.path().join("from_local");
        write(&from_local_filepath, &EXPECTED_DATA).unwrap();
        copy(
            storage_admin,
            from_local_filepath.display().to_string(),
            "123456::from_local".to_string(),
        )
        .await
    }

    #[fuchsia::test]
    async fn test_copy_local_to_device_populated_directory() -> Result<()> {
        let dir = tempdir().unwrap();
        let mut seed_files = HashMap::new();

        seed_files.insert("foo.txt", "Lorem Ipsum");

        let storage_admin = setup_fake_storage_admin_with_tmp("123456", seed_files);
        let from_local_filepath = dir.path().join("from_local");
        write(&from_local_filepath, &EXPECTED_DATA).unwrap();
        copy(
            storage_admin,
            from_local_filepath.display().to_string(),
            "123456::from_local".to_string(),
        )
        .await
    }

    #[fuchsia::test]
    async fn test_copy_device_to_local_infer_path() -> Result<()> {
        let dir = tempdir().unwrap();
        let storage_admin = setup_fake_storage_admin("123456", setup_fake_directory);
        let dest_filepath = dir.path();

        copy(storage_admin, "123456::from_device".to_string(), dest_filepath.display().to_string())
            .await?;

        let final_path = dest_filepath.join("from_device");
        let actual_data = read(final_path).unwrap();
        assert_eq!(actual_data, EXPECTED_DATA);
        Ok(())
    }

    #[fuchsia::test]
    async fn test_copy_device_to_local_infer_slash_path() -> Result<()> {
        let dir = tempdir().unwrap();
        let storage_admin = setup_fake_storage_admin("123456", setup_fake_directory);
        let dest_filepath = dir.path();

        copy(
            storage_admin,
            "123456::from_device".to_string(),
            dest_filepath.display().to_string() + "/",
        )
        .await?;

        let final_path = dest_filepath.join("from_device");
        let actual_data = read(final_path).unwrap();
        assert_eq!(actual_data, EXPECTED_DATA);
        Ok(())
    }

    #[fuchsia::test]
    async fn test_copy_device_to_local() -> Result<()> {
        let dir = tempdir().unwrap();
        let storage_admin = setup_fake_storage_admin("123456", setup_fake_directory);
        let dest_filepath = dir.path().join("from_device");
        copy(storage_admin, "123456::from_device".to_string(), dest_filepath.display().to_string())
            .await?;
        let actual_data = read(dest_filepath).unwrap();
        assert_eq!(actual_data, EXPECTED_DATA);
        Ok(())
    }
}