1use crate::common::{
8 decode_extended_attribute_value, encode_extended_attribute_value, extended_attributes_sender,
9 io1_to_io2_attrs,
10};
11use crate::directory::connection::{BaseConnection, ConnectionState};
12use crate::directory::entry_container::MutableDirectory;
13use crate::execution_scope::ExecutionScope;
14use crate::name::validate_name;
15use crate::node::OpenNode;
16use crate::object_request::ConnectionCreator;
17use crate::path::Path;
18use crate::request_handler::{RequestHandler, RequestListener};
19use crate::token_registry::{TokenInterface, TokenRegistry, Tokenizable};
20use crate::{ObjectRequestRef, ProtocolsExt};
21
22use anyhow::Error;
23use fidl::endpoints::ServerEnd;
24use fidl::Handle;
25use fidl_fuchsia_io as fio;
26use std::ops::ControlFlow;
27use std::pin::Pin;
28use std::sync::Arc;
29use storage_trace::{self as trace, TraceFutureExt};
30use zx_status::Status;
31
32pub struct MutableConnection<DirectoryType: MutableDirectory> {
33 base: BaseConnection<DirectoryType>,
34}
35
36impl<DirectoryType: MutableDirectory> MutableConnection<DirectoryType> {
37 pub async fn create(
43 scope: ExecutionScope,
44 directory: Arc<DirectoryType>,
45 protocols: impl ProtocolsExt,
46 object_request: ObjectRequestRef<'_>,
47 ) -> Result<(), Status> {
48 let directory = OpenNode::new(directory);
50
51 let connection = MutableConnection {
52 base: BaseConnection::new(scope.clone(), directory, protocols.to_directory_options()?),
53 };
54
55 if let Ok(requests) = object_request.take().into_request_stream(&connection.base).await {
56 scope.spawn(RequestListener::new(requests, Tokenizable::new(connection)));
57 }
58 Ok(())
59 }
60
61 async fn handle_request(
62 this: Pin<&mut Tokenizable<Self>>,
63 request: fio::DirectoryRequest,
64 ) -> Result<ConnectionState, Error> {
65 match request {
66 fio::DirectoryRequest::Unlink { name, options, responder } => {
67 let result = this.handle_unlink(name, options).await;
68 responder.send(result.map_err(Status::into_raw))?;
69 }
70 fio::DirectoryRequest::GetToken { responder } => {
71 let (status, token) = match Self::handle_get_token(this.into_ref()) {
72 Ok(token) => (Status::OK, Some(token)),
73 Err(status) => (status, None),
74 };
75 responder.send(status.into_raw(), token)?;
76 }
77 fio::DirectoryRequest::Rename { src, dst_parent_token, dst, responder } => {
78 let result = this.handle_rename(src, Handle::from(dst_parent_token), dst).await;
79 responder.send(result.map_err(Status::into_raw))?;
80 }
81 fio::DirectoryRequest::SetAttr { flags, attributes, responder } => {
82 let status = match this
83 .handle_update_attributes(io1_to_io2_attrs(flags, attributes))
84 .await
85 {
86 Ok(()) => Status::OK,
87 Err(status) => status,
88 };
89 responder.send(status.into_raw())?;
90 }
91 fio::DirectoryRequest::Sync { responder } => {
92 responder.send(this.base.directory.sync().await.map_err(Status::into_raw))?;
93 }
94 fio::DirectoryRequest::CreateSymlink {
95 responder, name, target, connection, ..
96 } => {
97 if !this.base.options.rights.contains(fio::Operations::MODIFY_DIRECTORY) {
98 responder.send(Err(Status::ACCESS_DENIED.into_raw()))?;
99 } else if validate_name(&name).is_err() {
100 responder.send(Err(Status::INVALID_ARGS.into_raw()))?;
101 } else {
102 responder.send(
103 this.base
104 .directory
105 .create_symlink(name, target, connection)
106 .await
107 .map_err(Status::into_raw),
108 )?;
109 }
110 }
111 fio::DirectoryRequest::ListExtendedAttributes { iterator, control_handle: _ } => {
112 this.handle_list_extended_attribute(iterator)
113 .trace(trace::trace_future_args!(
114 c"storage",
115 c"Directory::ListExtendedAttributes"
116 ))
117 .await;
118 }
119 fio::DirectoryRequest::GetExtendedAttribute { name, responder } => {
120 async move {
121 let res =
122 this.handle_get_extended_attribute(name).await.map_err(Status::into_raw);
123 responder.send(res)
124 }
125 .trace(trace::trace_future_args!(c"storage", c"Directory::GetExtendedAttribute"))
126 .await?;
127 }
128 fio::DirectoryRequest::SetExtendedAttribute { name, value, mode, responder } => {
129 async move {
130 let res = this
131 .handle_set_extended_attribute(name, value, mode)
132 .await
133 .map_err(Status::into_raw);
134 responder.send(res)
135 }
136 .trace(trace::trace_future_args!(c"storage", c"Directory::SetExtendedAttribute"))
137 .await?;
138 }
139 fio::DirectoryRequest::RemoveExtendedAttribute { name, responder } => {
140 async move {
141 let res =
142 this.handle_remove_extended_attribute(name).await.map_err(Status::into_raw);
143 responder.send(res)
144 }
145 .trace(trace::trace_future_args!(c"storage", c"Directory::RemoveExtendedAttribute"))
146 .await?;
147 }
148 fio::DirectoryRequest::UpdateAttributes { payload, responder } => {
149 async move {
150 responder.send(
151 this.handle_update_attributes(payload).await.map_err(Status::into_raw),
152 )
153 }
154 .trace(trace::trace_future_args!(c"storage", c"Directory::UpdateAttributes"))
155 .await?;
156 }
157 request => {
158 return this.as_mut().base.handle_request(request).await;
159 }
160 }
161 Ok(ConnectionState::Alive)
162 }
163
164 async fn handle_update_attributes(
165 &self,
166 attributes: fio::MutableNodeAttributes,
167 ) -> Result<(), Status> {
168 if !self.base.options.rights.contains(fio::Operations::UPDATE_ATTRIBUTES) {
169 return Err(Status::BAD_HANDLE);
170 }
171 self.base.directory.update_attributes(attributes).await
174 }
175
176 async fn handle_unlink(&self, name: String, options: fio::UnlinkOptions) -> Result<(), Status> {
177 if !self.base.options.rights.contains(fio::Rights::MODIFY_DIRECTORY) {
178 return Err(Status::BAD_HANDLE);
179 }
180
181 if name.is_empty() || name.contains('/') || name == "." || name == ".." {
182 return Err(Status::INVALID_ARGS);
183 }
184
185 self.base
186 .directory
187 .clone()
188 .unlink(
189 &name,
190 options
191 .flags
192 .map(|f| f.contains(fio::UnlinkFlags::MUST_BE_DIRECTORY))
193 .unwrap_or(false),
194 )
195 .await
196 }
197
198 fn handle_get_token(this: Pin<&Tokenizable<Self>>) -> Result<Handle, Status> {
199 if !this.base.options.rights.contains(fio::Rights::MODIFY_DIRECTORY) {
202 return Err(Status::BAD_HANDLE);
203 }
204 Ok(TokenRegistry::get_token(this)?)
205 }
206
207 async fn handle_rename(
208 &self,
209 src: String,
210 dst_parent_token: Handle,
211 dst: String,
212 ) -> Result<(), Status> {
213 if !self.base.options.rights.contains(fio::Rights::MODIFY_DIRECTORY) {
214 return Err(Status::BAD_HANDLE);
215 }
216
217 let src = Path::validate_and_split(src)?;
218 let dst = Path::validate_and_split(dst)?;
219
220 if !src.is_single_component() || !dst.is_single_component() {
221 return Err(Status::INVALID_ARGS);
222 }
223
224 let dst_parent = match self.base.scope.token_registry().get_owner(dst_parent_token)? {
225 None => return Err(Status::NOT_FOUND),
226 Some(entry) => entry,
227 };
228
229 dst_parent.clone().rename(self.base.directory.clone(), src, dst).await
230 }
231
232 async fn handle_list_extended_attribute(
233 &self,
234 iterator: ServerEnd<fio::ExtendedAttributeIteratorMarker>,
235 ) {
236 let attributes = match self.base.directory.list_extended_attributes().await {
237 Ok(attributes) => attributes,
238 Err(status) => {
239 log::error!(status:?; "list extended attributes failed");
240 iterator
241 .close_with_epitaph(status)
242 .unwrap_or_else(|error| log::error!(error:?; "failed to send epitaph"));
243 return;
244 }
245 };
246 self.base.scope.spawn(extended_attributes_sender(iterator, attributes));
247 }
248
249 async fn handle_get_extended_attribute(
250 &self,
251 name: Vec<u8>,
252 ) -> Result<fio::ExtendedAttributeValue, Status> {
253 let value = self.base.directory.get_extended_attribute(name).await?;
254 encode_extended_attribute_value(value)
255 }
256
257 async fn handle_set_extended_attribute(
258 &self,
259 name: Vec<u8>,
260 value: fio::ExtendedAttributeValue,
261 mode: fio::SetExtendedAttributeMode,
262 ) -> Result<(), Status> {
263 if name.contains(&0) {
264 return Err(Status::INVALID_ARGS);
265 }
266 let val = decode_extended_attribute_value(value)?;
267 self.base.directory.set_extended_attribute(name, val, mode).await
268 }
269
270 async fn handle_remove_extended_attribute(&self, name: Vec<u8>) -> Result<(), Status> {
271 self.base.directory.remove_extended_attribute(name).await
272 }
273}
274
275impl<DirectoryType: MutableDirectory> ConnectionCreator<DirectoryType>
276 for MutableConnection<DirectoryType>
277{
278 async fn create<'a>(
279 scope: ExecutionScope,
280 node: Arc<DirectoryType>,
281 protocols: impl ProtocolsExt,
282 object_request: ObjectRequestRef<'a>,
283 ) -> Result<(), Status> {
284 Self::create(scope, node, protocols, object_request).await
285 }
286}
287
288impl<DirectoryType: MutableDirectory> RequestHandler
289 for Tokenizable<MutableConnection<DirectoryType>>
290{
291 type Request = Result<fio::DirectoryRequest, fidl::Error>;
292
293 async fn handle_request(self: Pin<&mut Self>, request: Self::Request) -> ControlFlow<()> {
294 let _guard = self.base.scope.active_guard();
295 match request {
296 Ok(request) => {
297 match MutableConnection::<DirectoryType>::handle_request(self, request).await {
298 Ok(ConnectionState::Alive) => ControlFlow::Continue(()),
299 Ok(ConnectionState::Closed) | Err(_) => ControlFlow::Break(()),
300 }
301 }
302 Err(_) => ControlFlow::Break(()),
303 }
304 }
305}
306
307impl<DirectoryType: MutableDirectory> TokenInterface for MutableConnection<DirectoryType> {
308 fn get_node(&self) -> Arc<dyn MutableDirectory> {
309 self.base.directory.clone()
310 }
311
312 fn token_registry(&self) -> &TokenRegistry {
313 self.base.scope.token_registry()
314 }
315}
316
317#[cfg(test)]
318mod tests {
319 use super::*;
320 use crate::directory::dirents_sink;
321 use crate::directory::entry::{EntryInfo, GetEntryInfo};
322 use crate::directory::entry_container::{Directory, DirectoryWatcher};
323 use crate::directory::traversal_position::TraversalPosition;
324 use crate::node::Node;
325 use crate::ToObjectRequest;
326 use futures::future::BoxFuture;
327 use std::any::Any;
328 use std::future::ready;
329 use std::sync::{Mutex, Weak};
330
331 #[derive(Debug, PartialEq)]
332 enum MutableDirectoryAction {
333 Link { id: u32, path: String },
334 Unlink { id: u32, name: String },
335 Rename { id: u32, src_name: String, dst_dir: u32, dst_name: String },
336 UpdateAttributes { id: u32, attributes: fio::MutableNodeAttributes },
337 Sync,
338 Close,
339 }
340
341 #[derive(Debug)]
342 struct MockDirectory {
343 id: u32,
344 fs: Arc<MockFilesystem>,
345 }
346
347 impl MockDirectory {
348 pub fn new(id: u32, fs: Arc<MockFilesystem>) -> Arc<Self> {
349 Arc::new(MockDirectory { id, fs })
350 }
351 }
352
353 impl PartialEq for MockDirectory {
354 fn eq(&self, other: &Self) -> bool {
355 self.id == other.id
356 }
357 }
358
359 impl GetEntryInfo for MockDirectory {
360 fn entry_info(&self) -> EntryInfo {
361 EntryInfo::new(0, fio::DirentType::Directory)
362 }
363 }
364
365 impl Node for MockDirectory {
366 async fn get_attributes(
367 &self,
368 _query: fio::NodeAttributesQuery,
369 ) -> Result<fio::NodeAttributes2, Status> {
370 unimplemented!("Not implemented");
371 }
372
373 fn close(self: Arc<Self>) {
374 let _ = self.fs.handle_event(MutableDirectoryAction::Close);
375 }
376 }
377
378 impl Directory for MockDirectory {
379 fn open(
380 self: Arc<Self>,
381 _scope: ExecutionScope,
382 _flags: fio::OpenFlags,
383 _path: Path,
384 _server_end: ServerEnd<fio::NodeMarker>,
385 ) {
386 unimplemented!("Not implemented!");
387 }
388
389 fn open3(
390 self: Arc<Self>,
391 _scope: ExecutionScope,
392 _path: Path,
393 _flags: fio::Flags,
394 _object_request: ObjectRequestRef<'_>,
395 ) -> Result<(), Status> {
396 unimplemented!("Not implemented!");
397 }
398
399 async fn read_dirents<'a>(
400 &'a self,
401 _pos: &'a TraversalPosition,
402 _sink: Box<dyn dirents_sink::Sink>,
403 ) -> Result<(TraversalPosition, Box<dyn dirents_sink::Sealed>), Status> {
404 unimplemented!("Not implemented");
405 }
406
407 fn register_watcher(
408 self: Arc<Self>,
409 _scope: ExecutionScope,
410 _mask: fio::WatchMask,
411 _watcher: DirectoryWatcher,
412 ) -> Result<(), Status> {
413 unimplemented!("Not implemented");
414 }
415
416 fn unregister_watcher(self: Arc<Self>, _key: usize) {
417 unimplemented!("Not implemented");
418 }
419 }
420
421 impl MutableDirectory for MockDirectory {
422 fn link<'a>(
423 self: Arc<Self>,
424 path: String,
425 _source_dir: Arc<dyn Any + Send + Sync>,
426 _source_name: &'a str,
427 ) -> BoxFuture<'a, Result<(), Status>> {
428 let result = self.fs.handle_event(MutableDirectoryAction::Link { id: self.id, path });
429 Box::pin(ready(result))
430 }
431
432 async fn unlink(
433 self: Arc<Self>,
434 name: &str,
435 _must_be_directory: bool,
436 ) -> Result<(), Status> {
437 self.fs.handle_event(MutableDirectoryAction::Unlink {
438 id: self.id,
439 name: name.to_string(),
440 })
441 }
442
443 async fn update_attributes(
444 &self,
445 attributes: fio::MutableNodeAttributes,
446 ) -> Result<(), Status> {
447 self.fs
448 .handle_event(MutableDirectoryAction::UpdateAttributes { id: self.id, attributes })
449 }
450
451 async fn sync(&self) -> Result<(), Status> {
452 self.fs.handle_event(MutableDirectoryAction::Sync)
453 }
454
455 fn rename(
456 self: Arc<Self>,
457 src_dir: Arc<dyn MutableDirectory>,
458 src_name: Path,
459 dst_name: Path,
460 ) -> BoxFuture<'static, Result<(), Status>> {
461 let src_dir = src_dir.into_any().downcast::<MockDirectory>().unwrap();
462 let result = self.fs.handle_event(MutableDirectoryAction::Rename {
463 id: src_dir.id,
464 src_name: src_name.into_string(),
465 dst_dir: self.id,
466 dst_name: dst_name.into_string(),
467 });
468 Box::pin(ready(result))
469 }
470 }
471
472 struct Events(Mutex<Vec<MutableDirectoryAction>>);
473
474 impl Events {
475 fn new() -> Arc<Self> {
476 Arc::new(Events(Mutex::new(vec![])))
477 }
478 }
479
480 struct MockFilesystem {
481 cur_id: Mutex<u32>,
482 scope: ExecutionScope,
483 events: Weak<Events>,
484 }
485
486 impl MockFilesystem {
487 pub fn new(events: &Arc<Events>) -> Self {
488 let scope = ExecutionScope::new();
489 MockFilesystem { cur_id: Mutex::new(0), scope, events: Arc::downgrade(events) }
490 }
491
492 pub fn handle_event(&self, event: MutableDirectoryAction) -> Result<(), Status> {
493 self.events.upgrade().map(|x| x.0.lock().unwrap().push(event));
494 Ok(())
495 }
496
497 pub fn make_connection(
498 self: &Arc<Self>,
499 flags: fio::OpenFlags,
500 ) -> (Arc<MockDirectory>, fio::DirectoryProxy) {
501 let mut cur_id = self.cur_id.lock().unwrap();
502 let dir = MockDirectory::new(*cur_id, self.clone());
503 *cur_id += 1;
504 let (proxy, server_end) = fidl::endpoints::create_proxy::<fio::DirectoryMarker>();
505 flags.to_object_request(server_end).create_connection_sync::<MutableConnection<_>, _>(
506 self.scope.clone(),
507 dir.clone(),
508 flags,
509 );
510 (dir, proxy)
511 }
512 }
513
514 impl std::fmt::Debug for MockFilesystem {
515 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
516 f.debug_struct("MockFilesystem").field("cur_id", &self.cur_id).finish()
517 }
518 }
519
520 #[fuchsia::test]
521 async fn test_rename() {
522 use fidl::Event;
523
524 let events = Events::new();
525 let fs = Arc::new(MockFilesystem::new(&events));
526
527 let (_dir, proxy) = fs
528 .clone()
529 .make_connection(fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::RIGHT_WRITABLE);
530 let (dir2, proxy2) = fs
531 .clone()
532 .make_connection(fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::RIGHT_WRITABLE);
533
534 let (status, token) = proxy2.get_token().await.unwrap();
535 assert_eq!(Status::from_raw(status), Status::OK);
536
537 let status = proxy.rename("src", Event::from(token.unwrap()), "dest").await.unwrap();
538 assert!(status.is_ok());
539
540 let events = events.0.lock().unwrap();
541 assert_eq!(
542 *events,
543 vec![MutableDirectoryAction::Rename {
544 id: 0,
545 src_name: "src".to_owned(),
546 dst_dir: dir2.id,
547 dst_name: "dest".to_owned(),
548 },]
549 );
550 }
551
552 #[fuchsia::test]
553 async fn test_update_attributes() {
554 let events = Events::new();
555 let fs = Arc::new(MockFilesystem::new(&events));
556 let (_dir, proxy) = fs
557 .clone()
558 .make_connection(fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::RIGHT_WRITABLE);
559 let attributes = fio::MutableNodeAttributes {
560 creation_time: Some(30),
561 modification_time: Some(100),
562 mode: Some(200),
563 ..Default::default()
564 };
565 proxy
566 .update_attributes(&attributes)
567 .await
568 .expect("FIDL call failed")
569 .map_err(Status::from_raw)
570 .expect("update attributes failed");
571
572 let events = events.0.lock().unwrap();
573 assert_eq!(*events, vec![MutableDirectoryAction::UpdateAttributes { id: 0, attributes }]);
574 }
575
576 #[fuchsia::test]
577 async fn test_link() {
578 let events = Events::new();
579 let fs = Arc::new(MockFilesystem::new(&events));
580 let (_dir, proxy) = fs
581 .clone()
582 .make_connection(fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::RIGHT_WRITABLE);
583 let (_dir2, proxy2) = fs
584 .clone()
585 .make_connection(fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::RIGHT_WRITABLE);
586
587 let (status, token) = proxy2.get_token().await.unwrap();
588 assert_eq!(Status::from_raw(status), Status::OK);
589
590 let status = proxy.link("src", token.unwrap(), "dest").await.unwrap();
591 assert_eq!(Status::from_raw(status), Status::OK);
592 let events = events.0.lock().unwrap();
593 assert_eq!(*events, vec![MutableDirectoryAction::Link { id: 1, path: "dest".to_owned() },]);
594 }
595
596 #[fuchsia::test]
597 async fn test_unlink() {
598 let events = Events::new();
599 let fs = Arc::new(MockFilesystem::new(&events));
600 let (_dir, proxy) = fs
601 .clone()
602 .make_connection(fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::RIGHT_WRITABLE);
603 proxy
604 .unlink("test", &fio::UnlinkOptions::default())
605 .await
606 .expect("fidl call failed")
607 .expect("unlink failed");
608 let events = events.0.lock().unwrap();
609 assert_eq!(
610 *events,
611 vec![MutableDirectoryAction::Unlink { id: 0, name: "test".to_string() },]
612 );
613 }
614
615 #[fuchsia::test]
616 async fn test_sync() {
617 let events = Events::new();
618 let fs = Arc::new(MockFilesystem::new(&events));
619 let (_dir, proxy) = fs
620 .clone()
621 .make_connection(fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::RIGHT_WRITABLE);
622 let () = proxy.sync().await.unwrap().map_err(Status::from_raw).unwrap();
623 let events = events.0.lock().unwrap();
624 assert_eq!(*events, vec![MutableDirectoryAction::Sync]);
625 }
626
627 #[fuchsia::test]
628 async fn test_close() {
629 let events = Events::new();
630 let fs = Arc::new(MockFilesystem::new(&events));
631 let (_dir, proxy) = fs
632 .clone()
633 .make_connection(fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::RIGHT_WRITABLE);
634 let () = proxy.close().await.unwrap().map_err(Status::from_raw).unwrap();
635 let events = events.0.lock().unwrap();
636 assert_eq!(*events, vec![MutableDirectoryAction::Close]);
637 }
638
639 #[fuchsia::test]
640 async fn test_implicit_close() {
641 let events = Events::new();
642 let fs = Arc::new(MockFilesystem::new(&events));
643 let (_dir, _proxy) = fs
644 .clone()
645 .make_connection(fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::RIGHT_WRITABLE);
646
647 fs.scope.shutdown();
648 fs.scope.wait().await;
649
650 let events = events.0.lock().unwrap();
651 assert_eq!(*events, vec![MutableDirectoryAction::Close]);
652 }
653}