xref: /DragonOS/kernel/src/filesystem/vfs/open.rs (revision 79ad6e5ba4cf7fd624dfa91a1de35d7e60bdda43)
1 use alloc::sync::Arc;
2 use log::warn;
3 use system_error::SystemError;
4 
5 use super::{
6     fcntl::AtFlags,
7     file::{File, FileMode},
8     syscall::{ModeType, OpenHow, OpenHowResolve},
9     utils::{rsplit_path, user_path_at},
10     FileType, IndexNode, MAX_PATHLEN, ROOT_INODE, VFS_MAX_FOLLOW_SYMLINK_TIMES,
11 };
12 use crate::filesystem::vfs::syscall::UtimensFlags;
13 use crate::time::{syscall::PosixTimeval, PosixTimeSpec};
14 use crate::{
15     driver::base::block::SeekFrom, process::ProcessManager,
16     syscall::user_access::check_and_clone_cstr,
17 };
18 use alloc::string::String;
19 
20 pub(super) fn do_faccessat(
21     dirfd: i32,
22     path: *const u8,
23     mode: ModeType,
24     flags: u32,
25 ) -> Result<usize, SystemError> {
26     if (mode.bits() & (!ModeType::S_IRWXO.bits())) != 0 {
27         return Err(SystemError::EINVAL);
28     }
29 
30     if (flags
31         & (!((AtFlags::AT_EACCESS | AtFlags::AT_SYMLINK_NOFOLLOW | AtFlags::AT_EMPTY_PATH).bits()
32             as u32)))
33         != 0
34     {
35         return Err(SystemError::EINVAL);
36     }
37 
38     // let follow_symlink = flags & AtFlags::AT_SYMLINK_NOFOLLOW.bits() as u32 == 0;
39 
40     let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?;
41 
42     let (inode, path) = user_path_at(&ProcessManager::current_pcb(), dirfd, &path)?;
43 
44     // 如果找不到文件,则返回错误码ENOENT
45     let _inode = inode.lookup_follow_symlink(path.as_str(), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
46 
47     // todo: 接着完善(可以借鉴linux 6.1.9的do_faccessat)
48     return Ok(0);
49 }
50 
51 pub fn do_fchmodat(dirfd: i32, path: *const u8, _mode: ModeType) -> Result<usize, SystemError> {
52     let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?;
53 
54     let (inode, path) = user_path_at(&ProcessManager::current_pcb(), dirfd, &path)?;
55 
56     // 如果找不到文件,则返回错误码ENOENT
57     let _inode = inode.lookup_follow_symlink(path.as_str(), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
58 
59     warn!("do_fchmodat: not implemented yet\n");
60     // todo: 真正去改变文件的权限
61 
62     return Ok(0);
63 }
64 
65 pub(super) fn do_sys_open(
66     dfd: i32,
67     path: &str,
68     o_flags: FileMode,
69     mode: ModeType,
70     follow_symlink: bool,
71 ) -> Result<usize, SystemError> {
72     let how = OpenHow::new(o_flags, mode, OpenHowResolve::empty());
73     return do_sys_openat2(dfd, path, how, follow_symlink);
74 }
75 
76 fn do_sys_openat2(
77     dirfd: i32,
78     path: &str,
79     how: OpenHow,
80     follow_symlink: bool,
81 ) -> Result<usize, SystemError> {
82     // debug!("open path: {}, how: {:?}", path, how);
83     let path = path.trim();
84 
85     let (inode_begin, path) = user_path_at(&ProcessManager::current_pcb(), dirfd, path)?;
86     let inode: Result<Arc<dyn IndexNode>, SystemError> = inode_begin.lookup_follow_symlink(
87         &path,
88         if follow_symlink {
89             VFS_MAX_FOLLOW_SYMLINK_TIMES
90         } else {
91             0
92         },
93     );
94 
95     let inode: Arc<dyn IndexNode> = match inode {
96         Ok(inode) => inode,
97         Err(errno) => {
98             // 文件不存在,且需要创建
99             if how.o_flags.contains(FileMode::O_CREAT)
100                 && !how.o_flags.contains(FileMode::O_DIRECTORY)
101                 && errno == SystemError::ENOENT
102             {
103                 let (filename, parent_path) = rsplit_path(&path);
104                 // 查找父目录
105                 let parent_inode: Arc<dyn IndexNode> =
106                     ROOT_INODE().lookup(parent_path.unwrap_or("/"))?;
107                 // 创建文件
108                 let inode: Arc<dyn IndexNode> = parent_inode.create(
109                     filename,
110                     FileType::File,
111                     ModeType::from_bits_truncate(0o755),
112                 )?;
113                 inode
114             } else {
115                 // 不需要创建文件,因此返回错误码
116                 return Err(errno);
117             }
118         }
119     };
120 
121     let file_type: FileType = inode.metadata()?.file_type;
122     // 如果要打开的是文件夹,而目标不是文件夹
123     if how.o_flags.contains(FileMode::O_DIRECTORY) && file_type != FileType::Dir {
124         return Err(SystemError::ENOTDIR);
125     }
126 
127     // 创建文件对象
128 
129     let file: File = File::new(inode, how.o_flags)?;
130 
131     // 打开模式为“追加”
132     if how.o_flags.contains(FileMode::O_APPEND) {
133         file.lseek(SeekFrom::SeekEnd(0))?;
134     }
135 
136     // 如果O_TRUNC,并且,打开模式包含O_RDWR或O_WRONLY,清空文件
137     if how.o_flags.contains(FileMode::O_TRUNC)
138         && (how.o_flags.contains(FileMode::O_RDWR) || how.o_flags.contains(FileMode::O_WRONLY))
139         && file_type == FileType::File
140     {
141         file.ftruncate(0)?;
142     }
143     // 把文件对象存入pcb
144     let r = ProcessManager::current_pcb()
145         .fd_table()
146         .write()
147         .alloc_fd(file, None)
148         .map(|fd| fd as usize);
149 
150     return r;
151 }
152 
153 /// On Linux, futimens() is a library function implemented on top of
154 /// the utimensat() system call.  To support this, the Linux
155 /// utimensat() system call implements a nonstandard feature: if
156 /// pathname is NULL, then the call modifies the timestamps of the
157 /// file referred to by the file descriptor dirfd (which may refer to
158 /// any type of file).
159 pub fn do_utimensat(
160     dirfd: i32,
161     pathname: Option<String>,
162     times: Option<[PosixTimeSpec; 2]>,
163     flags: UtimensFlags,
164 ) -> Result<usize, SystemError> {
165     const UTIME_NOW: i64 = (1i64 << 30) - 1i64;
166     const UTIME_OMIT: i64 = (1i64 << 30) - 2i64;
167     // log::debug!("do_utimensat: dirfd:{}, pathname:{:?}, times:{:?}, flags:{:?}", dirfd, pathname, times, flags);
168     let inode = match pathname {
169         Some(path) => {
170             let (inode_begin, path) =
171                 user_path_at(&ProcessManager::current_pcb(), dirfd, path.as_str())?;
172             let inode = if flags.contains(UtimensFlags::AT_SYMLINK_NOFOLLOW) {
173                 inode_begin.lookup(path.as_str())?
174             } else {
175                 inode_begin.lookup_follow_symlink(path.as_str(), VFS_MAX_FOLLOW_SYMLINK_TIMES)?
176             };
177             inode
178         }
179         None => {
180             let binding = ProcessManager::current_pcb().fd_table();
181             let fd_table_guard = binding.write();
182             let file = fd_table_guard
183                 .get_file_by_fd(dirfd)
184                 .ok_or(SystemError::EBADF)?;
185             file.inode()
186         }
187     };
188     let now = PosixTimeSpec::now();
189     let mut meta = inode.metadata()?;
190 
191     if let Some([atime, mtime]) = times {
192         if atime.tv_nsec == UTIME_NOW {
193             meta.atime = now;
194         } else if atime.tv_nsec != UTIME_OMIT {
195             meta.atime = atime;
196         }
197         if mtime.tv_nsec == UTIME_NOW {
198             meta.mtime = now;
199         } else if mtime.tv_nsec != UTIME_OMIT {
200             meta.mtime = mtime;
201         }
202         inode.set_metadata(&meta).unwrap();
203     } else {
204         meta.atime = now;
205         meta.mtime = now;
206         inode.set_metadata(&meta).unwrap();
207     }
208     return Ok(0);
209 }
210 
211 pub fn do_utimes(path: &str, times: Option<[PosixTimeval; 2]>) -> Result<usize, SystemError> {
212     // log::debug!("do_utimes: path:{:?}, times:{:?}", path, times);
213     let (inode_begin, path) = user_path_at(
214         &ProcessManager::current_pcb(),
215         AtFlags::AT_FDCWD.bits(),
216         path,
217     )?;
218     let inode = inode_begin.lookup_follow_symlink(path.as_str(), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
219     let mut meta = inode.metadata()?;
220 
221     if let Some([atime, mtime]) = times {
222         meta.atime = PosixTimeSpec::from(atime);
223         meta.mtime = PosixTimeSpec::from(mtime);
224         inode.set_metadata(&meta)?;
225     } else {
226         let now = PosixTimeSpec::now();
227         meta.atime = now;
228         meta.mtime = now;
229         inode.set_metadata(&meta)?;
230     }
231     return Ok(0);
232 }
233