1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * linux/fs/namei.c
4 *
5 * Copyright (C) 1991, 1992 Linus Torvalds
6 */
7
8 /*
9 * Some corrections by tytso.
10 */
11
12 /* [Feb 1997 T. Schoebel-Theuer] Complete rewrite of the pathname
13 * lookup logic.
14 */
15 /* [Feb-Apr 2000, AV] Rewrite to the new namespace architecture.
16 */
17
18 #include <linux/init.h>
19 #include <linux/export.h>
20 #include <linux/slab.h>
21 #include <linux/wordpart.h>
22 #include <linux/fs.h>
23 #include <linux/filelock.h>
24 #include <linux/namei.h>
25 #include <linux/pagemap.h>
26 #include <linux/sched/mm.h>
27 #include <linux/fsnotify.h>
28 #include <linux/personality.h>
29 #include <linux/security.h>
30 #include <linux/syscalls.h>
31 #include <linux/mount.h>
32 #include <linux/audit.h>
33 #include <linux/capability.h>
34 #include <linux/file.h>
35 #include <linux/fcntl.h>
36 #include <linux/device_cgroup.h>
37 #include <linux/fs_struct.h>
38 #include <linux/posix_acl.h>
39 #include <linux/hash.h>
40 #include <linux/bitops.h>
41 #include <linux/init_task.h>
42 #include <linux/uaccess.h>
43
44 #include <asm/runtime-const.h>
45
46 #include "internal.h"
47 #include "mount.h"
48
49 /* [Feb-1997 T. Schoebel-Theuer]
50 * Fundamental changes in the pathname lookup mechanisms (namei)
51 * were necessary because of omirr. The reason is that omirr needs
52 * to know the _real_ pathname, not the user-supplied one, in case
53 * of symlinks (and also when transname replacements occur).
54 *
55 * The new code replaces the old recursive symlink resolution with
56 * an iterative one (in case of non-nested symlink chains). It does
57 * this with calls to <fs>_follow_link().
58 * As a side effect, dir_namei(), _namei() and follow_link() are now
59 * replaced with a single function lookup_dentry() that can handle all
60 * the special cases of the former code.
61 *
62 * With the new dcache, the pathname is stored at each inode, at least as
63 * long as the refcount of the inode is positive. As a side effect, the
64 * size of the dcache depends on the inode cache and thus is dynamic.
65 *
66 * [29-Apr-1998 C. Scott Ananian] Updated above description of symlink
67 * resolution to correspond with current state of the code.
68 *
69 * Note that the symlink resolution is not *completely* iterative.
70 * There is still a significant amount of tail- and mid- recursion in
71 * the algorithm. Also, note that <fs>_readlink() is not used in
72 * lookup_dentry(): lookup_dentry() on the result of <fs>_readlink()
73 * may return different results than <fs>_follow_link(). Many virtual
74 * filesystems (including /proc) exhibit this behavior.
75 */
76
77 /* [24-Feb-97 T. Schoebel-Theuer] Side effects caused by new implementation:
78 * New symlink semantics: when open() is called with flags O_CREAT | O_EXCL
79 * and the name already exists in form of a symlink, try to create the new
80 * name indicated by the symlink. The old code always complained that the
81 * name already exists, due to not following the symlink even if its target
82 * is nonexistent. The new semantics affects also mknod() and link() when
83 * the name is a symlink pointing to a non-existent name.
84 *
85 * I don't know which semantics is the right one, since I have no access
86 * to standards. But I found by trial that HP-UX 9.0 has the full "new"
87 * semantics implemented, while SunOS 4.1.1 and Solaris (SunOS 5.4) have the
88 * "old" one. Personally, I think the new semantics is much more logical.
89 * Note that "ln old new" where "new" is a symlink pointing to a non-existing
90 * file does succeed in both HP-UX and SunOs, but not in Solaris
91 * and in the old Linux semantics.
92 */
93
94 /* [16-Dec-97 Kevin Buhr] For security reasons, we change some symlink
95 * semantics. See the comments in "open_namei" and "do_link" below.
96 *
97 * [10-Sep-98 Alan Modra] Another symlink change.
98 */
99
100 /* [Feb-Apr 2000 AV] Complete rewrite. Rules for symlinks:
101 * inside the path - always follow.
102 * in the last component in creation/removal/renaming - never follow.
103 * if LOOKUP_FOLLOW passed - follow.
104 * if the pathname has trailing slashes - follow.
105 * otherwise - don't follow.
106 * (applied in that order).
107 *
108 * [Jun 2000 AV] Inconsistent behaviour of open() in case if flags==O_CREAT
109 * restored for 2.4. This is the last surviving part of old 4.2BSD bug.
110 * During the 2.4 we need to fix the userland stuff depending on it -
111 * hopefully we will be able to get rid of that wart in 2.5. So far only
112 * XEmacs seems to be relying on it...
113 */
114 /*
115 * [Sep 2001 AV] Single-semaphore locking scheme (kudos to David Holland)
116 * implemented. Let's see if raised priority of ->s_vfs_rename_mutex gives
117 * any extra contention...
118 */
119
120 /* In order to reduce some races, while at the same time doing additional
121 * checking and hopefully speeding things up, we copy filenames to the
122 * kernel data space before using them..
123 *
124 * POSIX.1 2.4: an empty pathname is invalid (ENOENT).
125 * PATH_MAX includes the nul terminator --RR.
126 */
127
128 /* SLAB cache for struct filename instances */
129 static struct kmem_cache *__names_cache __ro_after_init;
130 #define names_cache runtime_const_ptr(__names_cache)
131
132 /*
133 * Type of the last component on LOOKUP_PARENT
134 */
135 enum last_type {LAST_NORM, LAST_ROOT, LAST_DOT, LAST_DOTDOT};
136
filename_init(void)137 void __init filename_init(void)
138 {
139 __names_cache = kmem_cache_create_usercopy("names_cache", sizeof(struct filename), 0,
140 SLAB_HWCACHE_ALIGN|SLAB_PANIC, offsetof(struct filename, iname),
141 EMBEDDED_NAME_MAX, NULL);
142 runtime_const_init(ptr, __names_cache);
143 }
144
alloc_filename(void)145 static inline struct filename *alloc_filename(void)
146 {
147 return kmem_cache_alloc(names_cache, GFP_KERNEL);
148 }
149
free_filename(struct filename * p)150 static inline void free_filename(struct filename *p)
151 {
152 kmem_cache_free(names_cache, p);
153 }
154
initname(struct filename * name)155 static inline void initname(struct filename *name)
156 {
157 name->aname = NULL;
158 name->refcnt = 1;
159 }
160
getname_long(struct filename * name,const char __user * filename)161 static int getname_long(struct filename *name, const char __user *filename)
162 {
163 int len;
164 char *p __free(kfree) = kmalloc(PATH_MAX, GFP_KERNEL);
165 if (unlikely(!p))
166 return -ENOMEM;
167
168 memcpy(p, &name->iname, EMBEDDED_NAME_MAX);
169 len = strncpy_from_user(p + EMBEDDED_NAME_MAX,
170 filename + EMBEDDED_NAME_MAX,
171 PATH_MAX - EMBEDDED_NAME_MAX);
172 if (unlikely(len < 0))
173 return len;
174 if (unlikely(len == PATH_MAX - EMBEDDED_NAME_MAX))
175 return -ENAMETOOLONG;
176 name->name = no_free_ptr(p);
177 return 0;
178 }
179
180 static struct filename *
do_getname(const char __user * filename,int flags,bool incomplete)181 do_getname(const char __user *filename, int flags, bool incomplete)
182 {
183 struct filename *result;
184 char *kname;
185 int len;
186
187 result = alloc_filename();
188 if (unlikely(!result))
189 return ERR_PTR(-ENOMEM);
190
191 /*
192 * First, try to embed the struct filename inside the names_cache
193 * allocation
194 */
195 kname = (char *)result->iname;
196 result->name = kname;
197
198 len = strncpy_from_user(kname, filename, EMBEDDED_NAME_MAX);
199 /*
200 * Handle both empty path and copy failure in one go.
201 */
202 if (unlikely(len <= 0)) {
203 /* The empty path is special. */
204 if (!len && !(flags & LOOKUP_EMPTY))
205 len = -ENOENT;
206 }
207
208 /*
209 * Uh-oh. We have a name that's approaching PATH_MAX. Allocate a
210 * separate struct filename so we can dedicate the entire
211 * names_cache allocation for the pathname, and re-do the copy from
212 * userland.
213 */
214 if (unlikely(len == EMBEDDED_NAME_MAX))
215 len = getname_long(result, filename);
216 if (unlikely(len < 0)) {
217 free_filename(result);
218 return ERR_PTR(len);
219 }
220
221 initname(result);
222 if (likely(!incomplete))
223 audit_getname(result);
224 return result;
225 }
226
227 struct filename *
getname_flags(const char __user * filename,int flags)228 getname_flags(const char __user *filename, int flags)
229 {
230 return do_getname(filename, flags, false);
231 }
232
getname_uflags(const char __user * filename,int uflags)233 struct filename *getname_uflags(const char __user *filename, int uflags)
234 {
235 int flags = (uflags & AT_EMPTY_PATH) ? LOOKUP_EMPTY : 0;
236
237 return getname_flags(filename, flags);
238 }
239
__getname_maybe_null(const char __user * pathname)240 struct filename *__getname_maybe_null(const char __user *pathname)
241 {
242 char c;
243
244 /* try to save on allocations; loss on um, though */
245 if (get_user(c, pathname))
246 return ERR_PTR(-EFAULT);
247 if (!c)
248 return NULL;
249
250 CLASS(filename_flags, name)(pathname, LOOKUP_EMPTY);
251 /* empty pathname translates to NULL */
252 if (!IS_ERR(name) && !(name->name[0]))
253 return NULL;
254 return no_free_ptr(name);
255 }
256
do_getname_kernel(const char * filename,bool incomplete)257 static struct filename *do_getname_kernel(const char *filename, bool incomplete)
258 {
259 struct filename *result;
260 int len = strlen(filename) + 1;
261 char *p;
262
263 if (unlikely(len > PATH_MAX))
264 return ERR_PTR(-ENAMETOOLONG);
265
266 result = alloc_filename();
267 if (unlikely(!result))
268 return ERR_PTR(-ENOMEM);
269
270 if (len <= EMBEDDED_NAME_MAX) {
271 p = (char *)result->iname;
272 memcpy(p, filename, len);
273 } else {
274 p = kmemdup(filename, len, GFP_KERNEL);
275 if (unlikely(!p)) {
276 free_filename(result);
277 return ERR_PTR(-ENOMEM);
278 }
279 }
280 result->name = p;
281 initname(result);
282 if (likely(!incomplete))
283 audit_getname(result);
284 return result;
285 }
286
getname_kernel(const char * filename)287 struct filename *getname_kernel(const char *filename)
288 {
289 return do_getname_kernel(filename, false);
290 }
291 EXPORT_SYMBOL(getname_kernel);
292
putname(struct filename * name)293 void putname(struct filename *name)
294 {
295 int refcnt;
296
297 if (IS_ERR_OR_NULL(name))
298 return;
299
300 refcnt = name->refcnt;
301 if (unlikely(refcnt != 1)) {
302 if (WARN_ON_ONCE(!refcnt))
303 return;
304
305 name->refcnt--;
306 return;
307 }
308
309 if (unlikely(name->name != name->iname))
310 kfree(name->name);
311 free_filename(name);
312 }
313 EXPORT_SYMBOL(putname);
314
__delayed_getname(struct delayed_filename * v,const char __user * string,int flags)315 static inline int __delayed_getname(struct delayed_filename *v,
316 const char __user *string, int flags)
317 {
318 v->__incomplete_filename = do_getname(string, flags, true);
319 return PTR_ERR_OR_ZERO(v->__incomplete_filename);
320 }
321
delayed_getname(struct delayed_filename * v,const char __user * string)322 int delayed_getname(struct delayed_filename *v, const char __user *string)
323 {
324 return __delayed_getname(v, string, 0);
325 }
326
delayed_getname_uflags(struct delayed_filename * v,const char __user * string,int uflags)327 int delayed_getname_uflags(struct delayed_filename *v, const char __user *string,
328 int uflags)
329 {
330 int flags = (uflags & AT_EMPTY_PATH) ? LOOKUP_EMPTY : 0;
331 return __delayed_getname(v, string, flags);
332 }
333
putname_to_delayed(struct delayed_filename * v,struct filename * name)334 int putname_to_delayed(struct delayed_filename *v, struct filename *name)
335 {
336 if (likely(name->refcnt == 1)) {
337 v->__incomplete_filename = name;
338 return 0;
339 }
340 name->refcnt--;
341 v->__incomplete_filename = do_getname_kernel(name->name, true);
342 return PTR_ERR_OR_ZERO(v->__incomplete_filename);
343 }
344
dismiss_delayed_filename(struct delayed_filename * v)345 void dismiss_delayed_filename(struct delayed_filename *v)
346 {
347 putname(no_free_ptr(v->__incomplete_filename));
348 }
349
complete_getname(struct delayed_filename * v)350 struct filename *complete_getname(struct delayed_filename *v)
351 {
352 struct filename *res = no_free_ptr(v->__incomplete_filename);
353 if (!IS_ERR(res))
354 audit_getname(res);
355 return res;
356 }
357
358 /**
359 * check_acl - perform ACL permission checking
360 * @idmap: idmap of the mount the inode was found from
361 * @inode: inode to check permissions on
362 * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
363 *
364 * This function performs the ACL permission checking. Since this function
365 * retrieve POSIX acls it needs to know whether it is called from a blocking or
366 * non-blocking context and thus cares about the MAY_NOT_BLOCK bit.
367 *
368 * If the inode has been found through an idmapped mount the idmap of
369 * the vfsmount must be passed through @idmap. This function will then take
370 * care to map the inode according to @idmap before checking permissions.
371 * On non-idmapped mounts or if permission checking is to be performed on the
372 * raw inode simply pass @nop_mnt_idmap.
373 */
check_acl(struct mnt_idmap * idmap,struct inode * inode,int mask)374 static int check_acl(struct mnt_idmap *idmap,
375 struct inode *inode, int mask)
376 {
377 #ifdef CONFIG_FS_POSIX_ACL
378 struct posix_acl *acl;
379
380 if (mask & MAY_NOT_BLOCK) {
381 acl = get_cached_acl_rcu(inode, ACL_TYPE_ACCESS);
382 if (!acl)
383 return -EAGAIN;
384 /* no ->get_inode_acl() calls in RCU mode... */
385 if (is_uncached_acl(acl))
386 return -ECHILD;
387 return posix_acl_permission(idmap, inode, acl, mask);
388 }
389
390 acl = get_inode_acl(inode, ACL_TYPE_ACCESS);
391 if (IS_ERR(acl))
392 return PTR_ERR(acl);
393 if (acl) {
394 int error = posix_acl_permission(idmap, inode, acl, mask);
395 posix_acl_release(acl);
396 return error;
397 }
398 #endif
399
400 return -EAGAIN;
401 }
402
403 /*
404 * Very quick optimistic "we know we have no ACL's" check.
405 *
406 * Note that this is purely for ACL_TYPE_ACCESS, and purely
407 * for the "we have cached that there are no ACLs" case.
408 *
409 * If this returns true, we know there are no ACLs. But if
410 * it returns false, we might still not have ACLs (it could
411 * be the is_uncached_acl() case).
412 */
no_acl_inode(struct inode * inode)413 static inline bool no_acl_inode(struct inode *inode)
414 {
415 #ifdef CONFIG_FS_POSIX_ACL
416 return likely(!READ_ONCE(inode->i_acl));
417 #else
418 return true;
419 #endif
420 }
421
422 /**
423 * acl_permission_check - perform basic UNIX permission checking
424 * @idmap: idmap of the mount the inode was found from
425 * @inode: inode to check permissions on
426 * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
427 *
428 * This function performs the basic UNIX permission checking. Since this
429 * function may retrieve POSIX acls it needs to know whether it is called from a
430 * blocking or non-blocking context and thus cares about the MAY_NOT_BLOCK bit.
431 *
432 * If the inode has been found through an idmapped mount the idmap of
433 * the vfsmount must be passed through @idmap. This function will then take
434 * care to map the inode according to @idmap before checking permissions.
435 * On non-idmapped mounts or if permission checking is to be performed on the
436 * raw inode simply pass @nop_mnt_idmap.
437 */
acl_permission_check(struct mnt_idmap * idmap,struct inode * inode,int mask)438 static int acl_permission_check(struct mnt_idmap *idmap,
439 struct inode *inode, int mask)
440 {
441 unsigned int mode = inode->i_mode;
442 vfsuid_t vfsuid;
443
444 /*
445 * Common cheap case: everybody has the requested
446 * rights, and there are no ACLs to check. No need
447 * to do any owner/group checks in that case.
448 *
449 * - 'mask&7' is the requested permission bit set
450 * - multiplying by 0111 spreads them out to all of ugo
451 * - '& ~mode' looks for missing inode permission bits
452 * - the '!' is for "no missing permissions"
453 *
454 * After that, we just need to check that there are no
455 * ACL's on the inode - do the 'IS_POSIXACL()' check last
456 * because it will dereference the ->i_sb pointer and we
457 * want to avoid that if at all possible.
458 */
459 if (!((mask & 7) * 0111 & ~mode)) {
460 if (no_acl_inode(inode))
461 return 0;
462 if (!IS_POSIXACL(inode))
463 return 0;
464 }
465
466 /* Are we the owner? If so, ACL's don't matter */
467 vfsuid = i_uid_into_vfsuid(idmap, inode);
468 if (likely(vfsuid_eq_kuid(vfsuid, current_fsuid()))) {
469 mask &= 7;
470 mode >>= 6;
471 return (mask & ~mode) ? -EACCES : 0;
472 }
473
474 /* Do we have ACL's? */
475 if (IS_POSIXACL(inode) && (mode & S_IRWXG)) {
476 int error = check_acl(idmap, inode, mask);
477 if (error != -EAGAIN)
478 return error;
479 }
480
481 /* Only RWX matters for group/other mode bits */
482 mask &= 7;
483
484 /*
485 * Are the group permissions different from
486 * the other permissions in the bits we care
487 * about? Need to check group ownership if so.
488 */
489 if (mask & (mode ^ (mode >> 3))) {
490 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
491 if (vfsgid_in_group_p(vfsgid))
492 mode >>= 3;
493 }
494
495 /* Bits in 'mode' clear that we require? */
496 return (mask & ~mode) ? -EACCES : 0;
497 }
498
499 /**
500 * generic_permission - check for access rights on a Posix-like filesystem
501 * @idmap: idmap of the mount the inode was found from
502 * @inode: inode to check access rights for
503 * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC,
504 * %MAY_NOT_BLOCK ...)
505 *
506 * Used to check for read/write/execute permissions on a file.
507 * We use "fsuid" for this, letting us set arbitrary permissions
508 * for filesystem access without changing the "normal" uids which
509 * are used for other things.
510 *
511 * generic_permission is rcu-walk aware. It returns -ECHILD in case an rcu-walk
512 * request cannot be satisfied (eg. requires blocking or too much complexity).
513 * It would then be called again in ref-walk mode.
514 *
515 * If the inode has been found through an idmapped mount the idmap of
516 * the vfsmount must be passed through @idmap. This function will then take
517 * care to map the inode according to @idmap before checking permissions.
518 * On non-idmapped mounts or if permission checking is to be performed on the
519 * raw inode simply pass @nop_mnt_idmap.
520 */
generic_permission(struct mnt_idmap * idmap,struct inode * inode,int mask)521 int generic_permission(struct mnt_idmap *idmap, struct inode *inode,
522 int mask)
523 {
524 int ret;
525
526 /*
527 * Do the basic permission checks.
528 */
529 ret = acl_permission_check(idmap, inode, mask);
530 if (ret != -EACCES)
531 return ret;
532
533 if (S_ISDIR(inode->i_mode)) {
534 /* DACs are overridable for directories */
535 if (!(mask & MAY_WRITE))
536 if (capable_wrt_inode_uidgid(idmap, inode,
537 CAP_DAC_READ_SEARCH))
538 return 0;
539 if (capable_wrt_inode_uidgid(idmap, inode,
540 CAP_DAC_OVERRIDE))
541 return 0;
542 return -EACCES;
543 }
544
545 /*
546 * Searching includes executable on directories, else just read.
547 */
548 mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
549 if (mask == MAY_READ)
550 if (capable_wrt_inode_uidgid(idmap, inode,
551 CAP_DAC_READ_SEARCH))
552 return 0;
553 /*
554 * Read/write DACs are always overridable.
555 * Executable DACs are overridable when there is
556 * at least one exec bit set.
557 */
558 if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO))
559 if (capable_wrt_inode_uidgid(idmap, inode,
560 CAP_DAC_OVERRIDE))
561 return 0;
562
563 return -EACCES;
564 }
565 EXPORT_SYMBOL(generic_permission);
566
567 /**
568 * do_inode_permission - UNIX permission checking
569 * @idmap: idmap of the mount the inode was found from
570 * @inode: inode to check permissions on
571 * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC ...)
572 *
573 * We _really_ want to just do "generic_permission()" without
574 * even looking at the inode->i_op values. So we keep a cache
575 * flag in inode->i_opflags, that says "this has not special
576 * permission function, use the fast case".
577 */
do_inode_permission(struct mnt_idmap * idmap,struct inode * inode,int mask)578 static inline int do_inode_permission(struct mnt_idmap *idmap,
579 struct inode *inode, int mask)
580 {
581 if (unlikely(!(inode->i_opflags & IOP_FASTPERM))) {
582 if (likely(inode->i_op->permission))
583 return inode->i_op->permission(idmap, inode, mask);
584
585 /* This gets set once for the inode lifetime */
586 spin_lock(&inode->i_lock);
587 inode->i_opflags |= IOP_FASTPERM;
588 spin_unlock(&inode->i_lock);
589 }
590 return generic_permission(idmap, inode, mask);
591 }
592
593 /**
594 * sb_permission - Check superblock-level permissions
595 * @sb: Superblock of inode to check permission on
596 * @inode: Inode to check permission on
597 * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
598 *
599 * Separate out file-system wide checks from inode-specific permission checks.
600 *
601 * Note: lookup_inode_permission_may_exec() does not call here. If you add
602 * MAY_EXEC checks, adjust it.
603 */
sb_permission(struct super_block * sb,struct inode * inode,int mask)604 static int sb_permission(struct super_block *sb, struct inode *inode, int mask)
605 {
606 if (mask & MAY_WRITE) {
607 umode_t mode = inode->i_mode;
608
609 /* Nobody gets write access to a read-only fs. */
610 if (sb_rdonly(sb) && (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)))
611 return -EROFS;
612 }
613 return 0;
614 }
615
616 /**
617 * inode_permission - Check for access rights to a given inode
618 * @idmap: idmap of the mount the inode was found from
619 * @inode: Inode to check permission on
620 * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
621 *
622 * Check for read/write/execute permissions on an inode. We use fs[ug]id for
623 * this, letting us set arbitrary permissions for filesystem access without
624 * changing the "normal" UIDs which are used for other things.
625 *
626 * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask.
627 */
inode_permission(struct mnt_idmap * idmap,struct inode * inode,int mask)628 int inode_permission(struct mnt_idmap *idmap,
629 struct inode *inode, int mask)
630 {
631 int retval;
632
633 retval = sb_permission(inode->i_sb, inode, mask);
634 if (unlikely(retval))
635 return retval;
636
637 if (mask & MAY_WRITE) {
638 /*
639 * Nobody gets write access to an immutable file.
640 */
641 if (unlikely(IS_IMMUTABLE(inode)))
642 return -EPERM;
643
644 /*
645 * Updating mtime will likely cause i_uid and i_gid to be
646 * written back improperly if their true value is unknown
647 * to the vfs.
648 */
649 if (unlikely(HAS_UNMAPPED_ID(idmap, inode)))
650 return -EACCES;
651 }
652
653 retval = do_inode_permission(idmap, inode, mask);
654 if (unlikely(retval))
655 return retval;
656
657 retval = devcgroup_inode_permission(inode, mask);
658 if (unlikely(retval))
659 return retval;
660
661 return security_inode_permission(inode, mask);
662 }
663 EXPORT_SYMBOL(inode_permission);
664
665 /*
666 * lookup_inode_permission_may_exec - Check traversal right for given inode
667 *
668 * This is a special case routine for may_lookup() making assumptions specific
669 * to path traversal. Use inode_permission() if you are doing something else.
670 *
671 * Work is shaved off compared to inode_permission() as follows:
672 * - we know for a fact there is no MAY_WRITE to worry about
673 * - it is an invariant the inode is a directory
674 *
675 * Since majority of real-world traversal happens on inodes which grant it for
676 * everyone, we check it upfront and only resort to more expensive work if it
677 * fails.
678 *
679 * Filesystems which have their own ->permission hook and consequently miss out
680 * on IOP_FASTPERM can still get the optimization if they set IOP_FASTPERM_MAY_EXEC
681 * on their directory inodes.
682 */
lookup_inode_permission_may_exec(struct mnt_idmap * idmap,struct inode * inode,int mask)683 static __always_inline int lookup_inode_permission_may_exec(struct mnt_idmap *idmap,
684 struct inode *inode, int mask)
685 {
686 /* Lookup already checked this to return -ENOTDIR */
687 VFS_BUG_ON_INODE(!S_ISDIR(inode->i_mode), inode);
688 VFS_BUG_ON((mask & ~MAY_NOT_BLOCK) != 0);
689
690 mask |= MAY_EXEC;
691
692 if (unlikely(!(inode->i_opflags & (IOP_FASTPERM | IOP_FASTPERM_MAY_EXEC))))
693 return inode_permission(idmap, inode, mask);
694
695 if (unlikely(((inode->i_mode & 0111) != 0111) || !no_acl_inode(inode)))
696 return inode_permission(idmap, inode, mask);
697
698 return security_inode_permission(inode, mask);
699 }
700
701 /**
702 * path_get - get a reference to a path
703 * @path: path to get the reference to
704 *
705 * Given a path increment the reference count to the dentry and the vfsmount.
706 */
path_get(const struct path * path)707 void path_get(const struct path *path)
708 {
709 mntget(path->mnt);
710 dget(path->dentry);
711 }
712 EXPORT_SYMBOL(path_get);
713
714 /**
715 * path_put - put a reference to a path
716 * @path: path to put the reference to
717 *
718 * Given a path decrement the reference count to the dentry and the vfsmount.
719 */
path_put(const struct path * path)720 void path_put(const struct path *path)
721 {
722 dput(path->dentry);
723 mntput(path->mnt);
724 }
725 EXPORT_SYMBOL(path_put);
726
727 #define EMBEDDED_LEVELS 2
728 struct nameidata {
729 struct path path;
730 struct qstr last;
731 struct path root;
732 struct inode *inode; /* path.dentry.d_inode */
733 unsigned int flags, state;
734 unsigned seq, next_seq, m_seq, r_seq;
735 enum last_type last_type;
736 unsigned depth;
737 int total_link_count;
738 struct saved {
739 struct path link;
740 struct delayed_call done;
741 const char *name;
742 unsigned seq;
743 } *stack, internal[EMBEDDED_LEVELS];
744 struct filename *name;
745 const char *pathname;
746 struct nameidata *saved;
747 unsigned root_seq;
748 int dfd;
749 vfsuid_t dir_vfsuid;
750 umode_t dir_mode;
751 } __randomize_layout;
752
753 #define ND_ROOT_PRESET 1
754 #define ND_ROOT_GRABBED 2
755 #define ND_JUMPED 4
756
__set_nameidata(struct nameidata * p,int dfd,struct filename * name)757 static void __set_nameidata(struct nameidata *p, int dfd, struct filename *name)
758 {
759 struct nameidata *old = current->nameidata;
760 p->stack = p->internal;
761 p->depth = 0;
762 p->dfd = dfd;
763 p->name = name;
764 p->pathname = likely(name) ? name->name : "";
765 p->path.mnt = NULL;
766 p->path.dentry = NULL;
767 p->total_link_count = old ? old->total_link_count : 0;
768 p->saved = old;
769 current->nameidata = p;
770 }
771
set_nameidata(struct nameidata * p,int dfd,struct filename * name,const struct path * root)772 static inline void set_nameidata(struct nameidata *p, int dfd, struct filename *name,
773 const struct path *root)
774 {
775 __set_nameidata(p, dfd, name);
776 p->state = 0;
777 if (unlikely(root)) {
778 p->state = ND_ROOT_PRESET;
779 p->root = *root;
780 }
781 }
782
restore_nameidata(void)783 static void restore_nameidata(void)
784 {
785 struct nameidata *now = current->nameidata, *old = now->saved;
786
787 current->nameidata = old;
788 if (old)
789 old->total_link_count = now->total_link_count;
790 if (now->stack != now->internal)
791 kfree(now->stack);
792 }
793
nd_alloc_stack(struct nameidata * nd)794 static bool nd_alloc_stack(struct nameidata *nd)
795 {
796 struct saved *p;
797
798 p= kmalloc_objs(struct saved, MAXSYMLINKS,
799 nd->flags & LOOKUP_RCU ? GFP_ATOMIC : GFP_KERNEL);
800 if (unlikely(!p))
801 return false;
802 memcpy(p, nd->internal, sizeof(nd->internal));
803 nd->stack = p;
804 return true;
805 }
806
807 /**
808 * path_connected - Verify that a dentry is below mnt.mnt_root
809 * @mnt: The mountpoint to check.
810 * @dentry: The dentry to check.
811 *
812 * Rename can sometimes move a file or directory outside of a bind
813 * mount, path_connected allows those cases to be detected.
814 */
path_connected(struct vfsmount * mnt,struct dentry * dentry)815 static bool path_connected(struct vfsmount *mnt, struct dentry *dentry)
816 {
817 struct super_block *sb = mnt->mnt_sb;
818
819 /* Bind mounts can have disconnected paths */
820 if (mnt->mnt_root == sb->s_root)
821 return true;
822
823 return is_subdir(dentry, mnt->mnt_root);
824 }
825
drop_links(struct nameidata * nd)826 static void drop_links(struct nameidata *nd)
827 {
828 int i = nd->depth;
829 while (i--) {
830 struct saved *last = nd->stack + i;
831 do_delayed_call(&last->done);
832 clear_delayed_call(&last->done);
833 }
834 }
835
leave_rcu(struct nameidata * nd)836 static void leave_rcu(struct nameidata *nd)
837 {
838 nd->flags &= ~LOOKUP_RCU;
839 nd->seq = nd->next_seq = 0;
840 rcu_read_unlock();
841 }
842
terminate_walk(struct nameidata * nd)843 static void terminate_walk(struct nameidata *nd)
844 {
845 if (unlikely(nd->depth))
846 drop_links(nd);
847 if (!(nd->flags & LOOKUP_RCU)) {
848 int i;
849 path_put(&nd->path);
850 for (i = 0; i < nd->depth; i++)
851 path_put(&nd->stack[i].link);
852 if (nd->state & ND_ROOT_GRABBED) {
853 path_put(&nd->root);
854 nd->state &= ~ND_ROOT_GRABBED;
855 }
856 } else {
857 leave_rcu(nd);
858 }
859 nd->depth = 0;
860 nd->path.mnt = NULL;
861 nd->path.dentry = NULL;
862 }
863
864 /* path_put is needed afterwards regardless of success or failure */
__legitimize_path(struct path * path,unsigned seq,unsigned mseq)865 static bool __legitimize_path(struct path *path, unsigned seq, unsigned mseq)
866 {
867 int res = __legitimize_mnt(path->mnt, mseq);
868 if (unlikely(res)) {
869 if (res > 0)
870 path->mnt = NULL;
871 path->dentry = NULL;
872 return false;
873 }
874 if (unlikely(!lockref_get_not_dead(&path->dentry->d_lockref))) {
875 path->dentry = NULL;
876 return false;
877 }
878 return !read_seqcount_retry(&path->dentry->d_seq, seq);
879 }
880
legitimize_path(struct nameidata * nd,struct path * path,unsigned seq)881 static inline bool legitimize_path(struct nameidata *nd,
882 struct path *path, unsigned seq)
883 {
884 return __legitimize_path(path, seq, nd->m_seq);
885 }
886
legitimize_links(struct nameidata * nd)887 static bool legitimize_links(struct nameidata *nd)
888 {
889 int i;
890
891 VFS_BUG_ON(nd->flags & LOOKUP_CACHED);
892
893 for (i = 0; i < nd->depth; i++) {
894 struct saved *last = nd->stack + i;
895 if (unlikely(!legitimize_path(nd, &last->link, last->seq))) {
896 drop_links(nd);
897 nd->depth = i + 1;
898 return false;
899 }
900 }
901 return true;
902 }
903
legitimize_root(struct nameidata * nd)904 static bool legitimize_root(struct nameidata *nd)
905 {
906 /* Nothing to do if nd->root is zero or is managed by the VFS user. */
907 if (!nd->root.mnt || (nd->state & ND_ROOT_PRESET))
908 return true;
909 nd->state |= ND_ROOT_GRABBED;
910 return legitimize_path(nd, &nd->root, nd->root_seq);
911 }
912
913 /*
914 * Path walking has 2 modes, rcu-walk and ref-walk (see
915 * Documentation/filesystems/path-lookup.txt). In situations when we can't
916 * continue in RCU mode, we attempt to drop out of rcu-walk mode and grab
917 * normal reference counts on dentries and vfsmounts to transition to ref-walk
918 * mode. Refcounts are grabbed at the last known good point before rcu-walk
919 * got stuck, so ref-walk may continue from there. If this is not successful
920 * (eg. a seqcount has changed), then failure is returned and it's up to caller
921 * to restart the path walk from the beginning in ref-walk mode.
922 */
923
924 /**
925 * try_to_unlazy - try to switch to ref-walk mode.
926 * @nd: nameidata pathwalk data
927 * Returns: true on success, false on failure
928 *
929 * try_to_unlazy attempts to legitimize the current nd->path and nd->root
930 * for ref-walk mode.
931 * Must be called from rcu-walk context.
932 * Nothing should touch nameidata between try_to_unlazy() failure and
933 * terminate_walk().
934 */
try_to_unlazy(struct nameidata * nd)935 static bool try_to_unlazy(struct nameidata *nd)
936 {
937 struct dentry *parent = nd->path.dentry;
938
939 VFS_BUG_ON(!(nd->flags & LOOKUP_RCU));
940
941 if (unlikely(nd->flags & LOOKUP_CACHED)) {
942 drop_links(nd);
943 nd->depth = 0;
944 goto out1;
945 }
946 if (unlikely(nd->depth && !legitimize_links(nd)))
947 goto out1;
948 if (unlikely(!legitimize_path(nd, &nd->path, nd->seq)))
949 goto out;
950 if (unlikely(!legitimize_root(nd)))
951 goto out;
952 leave_rcu(nd);
953 BUG_ON(nd->inode != parent->d_inode);
954 return true;
955
956 out1:
957 nd->path.mnt = NULL;
958 nd->path.dentry = NULL;
959 out:
960 leave_rcu(nd);
961 return false;
962 }
963
964 /**
965 * try_to_unlazy_next - try to switch to ref-walk mode.
966 * @nd: nameidata pathwalk data
967 * @dentry: next dentry to step into
968 * Returns: true on success, false on failure
969 *
970 * Similar to try_to_unlazy(), but here we have the next dentry already
971 * picked by rcu-walk and want to legitimize that in addition to the current
972 * nd->path and nd->root for ref-walk mode. Must be called from rcu-walk context.
973 * Nothing should touch nameidata between try_to_unlazy_next() failure and
974 * terminate_walk().
975 */
try_to_unlazy_next(struct nameidata * nd,struct dentry * dentry)976 static bool try_to_unlazy_next(struct nameidata *nd, struct dentry *dentry)
977 {
978 int res;
979
980 VFS_BUG_ON(!(nd->flags & LOOKUP_RCU));
981
982 if (unlikely(nd->flags & LOOKUP_CACHED)) {
983 drop_links(nd);
984 nd->depth = 0;
985 goto out2;
986 }
987 if (unlikely(nd->depth && !legitimize_links(nd)))
988 goto out2;
989 res = __legitimize_mnt(nd->path.mnt, nd->m_seq);
990 if (unlikely(res)) {
991 if (res > 0)
992 goto out2;
993 goto out1;
994 }
995 if (unlikely(!lockref_get_not_dead(&nd->path.dentry->d_lockref)))
996 goto out1;
997
998 /*
999 * We need to move both the parent and the dentry from the RCU domain
1000 * to be properly refcounted. And the sequence number in the dentry
1001 * validates *both* dentry counters, since we checked the sequence
1002 * number of the parent after we got the child sequence number. So we
1003 * know the parent must still be valid if the child sequence number is
1004 */
1005 if (unlikely(!lockref_get_not_dead(&dentry->d_lockref)))
1006 goto out;
1007 if (read_seqcount_retry(&dentry->d_seq, nd->next_seq))
1008 goto out_dput;
1009 /*
1010 * Sequence counts matched. Now make sure that the root is
1011 * still valid and get it if required.
1012 */
1013 if (unlikely(!legitimize_root(nd)))
1014 goto out_dput;
1015 leave_rcu(nd);
1016 return true;
1017
1018 out2:
1019 nd->path.mnt = NULL;
1020 out1:
1021 nd->path.dentry = NULL;
1022 out:
1023 leave_rcu(nd);
1024 return false;
1025 out_dput:
1026 leave_rcu(nd);
1027 dput(dentry);
1028 return false;
1029 }
1030
d_revalidate(struct inode * dir,const struct qstr * name,struct dentry * dentry,unsigned int flags)1031 static inline int d_revalidate(struct inode *dir, const struct qstr *name,
1032 struct dentry *dentry, unsigned int flags)
1033 {
1034 if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE))
1035 return dentry->d_op->d_revalidate(dir, name, dentry, flags);
1036 else
1037 return 1;
1038 }
1039
1040 /**
1041 * complete_walk - successful completion of path walk
1042 * @nd: pointer nameidata
1043 *
1044 * If we had been in RCU mode, drop out of it and legitimize nd->path.
1045 * Revalidate the final result, unless we'd already done that during
1046 * the path walk or the filesystem doesn't ask for it. Return 0 on
1047 * success, -error on failure. In case of failure caller does not
1048 * need to drop nd->path.
1049 */
complete_walk(struct nameidata * nd)1050 static int complete_walk(struct nameidata *nd)
1051 {
1052 struct dentry *dentry = nd->path.dentry;
1053 int status;
1054
1055 if (nd->flags & LOOKUP_RCU) {
1056 /*
1057 * We don't want to zero nd->root for scoped-lookups or
1058 * externally-managed nd->root.
1059 */
1060 if (likely(!(nd->state & ND_ROOT_PRESET)))
1061 if (likely(!(nd->flags & LOOKUP_IS_SCOPED)))
1062 nd->root.mnt = NULL;
1063 nd->flags &= ~LOOKUP_CACHED;
1064 if (!try_to_unlazy(nd))
1065 return -ECHILD;
1066 }
1067
1068 if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
1069 /*
1070 * While the guarantee of LOOKUP_IS_SCOPED is (roughly) "don't
1071 * ever step outside the root during lookup" and should already
1072 * be guaranteed by the rest of namei, we want to avoid a namei
1073 * BUG resulting in userspace being given a path that was not
1074 * scoped within the root at some point during the lookup.
1075 *
1076 * So, do a final sanity-check to make sure that in the
1077 * worst-case scenario (a complete bypass of LOOKUP_IS_SCOPED)
1078 * we won't silently return an fd completely outside of the
1079 * requested root to userspace.
1080 *
1081 * Userspace could move the path outside the root after this
1082 * check, but as discussed elsewhere this is not a concern (the
1083 * resolved file was inside the root at some point).
1084 */
1085 if (!path_is_under(&nd->path, &nd->root))
1086 return -EXDEV;
1087 }
1088
1089 if (likely(!(nd->state & ND_JUMPED)))
1090 return 0;
1091
1092 if (likely(!(dentry->d_flags & DCACHE_OP_WEAK_REVALIDATE)))
1093 return 0;
1094
1095 status = dentry->d_op->d_weak_revalidate(dentry, nd->flags);
1096 if (status > 0)
1097 return 0;
1098
1099 if (!status)
1100 status = -ESTALE;
1101
1102 return status;
1103 }
1104
set_root(struct nameidata * nd)1105 static int set_root(struct nameidata *nd)
1106 {
1107 struct fs_struct *fs = current->fs;
1108
1109 /*
1110 * Jumping to the real root in a scoped-lookup is a BUG in namei, but we
1111 * still have to ensure it doesn't happen because it will cause a breakout
1112 * from the dirfd.
1113 */
1114 if (WARN_ON(nd->flags & LOOKUP_IS_SCOPED))
1115 return -ENOTRECOVERABLE;
1116
1117 if (nd->flags & LOOKUP_RCU) {
1118 unsigned seq;
1119
1120 do {
1121 seq = read_seqbegin(&fs->seq);
1122 nd->root = fs->root;
1123 nd->root_seq = __read_seqcount_begin(&nd->root.dentry->d_seq);
1124 } while (read_seqretry(&fs->seq, seq));
1125 } else {
1126 get_fs_root(fs, &nd->root);
1127 nd->state |= ND_ROOT_GRABBED;
1128 }
1129 return 0;
1130 }
1131
nd_jump_root(struct nameidata * nd)1132 static int nd_jump_root(struct nameidata *nd)
1133 {
1134 if (unlikely(nd->flags & LOOKUP_BENEATH))
1135 return -EXDEV;
1136 if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
1137 /* Absolute path arguments to path_init() are allowed. */
1138 if (nd->path.mnt != NULL && nd->path.mnt != nd->root.mnt)
1139 return -EXDEV;
1140 }
1141 if (!nd->root.mnt) {
1142 int error = set_root(nd);
1143 if (unlikely(error))
1144 return error;
1145 }
1146 if (nd->flags & LOOKUP_RCU) {
1147 struct dentry *d;
1148 nd->path = nd->root;
1149 d = nd->path.dentry;
1150 nd->inode = d->d_inode;
1151 nd->seq = nd->root_seq;
1152 if (read_seqcount_retry(&d->d_seq, nd->seq))
1153 return -ECHILD;
1154 } else {
1155 path_put(&nd->path);
1156 nd->path = nd->root;
1157 path_get(&nd->path);
1158 nd->inode = nd->path.dentry->d_inode;
1159 }
1160 nd->state |= ND_JUMPED;
1161 return 0;
1162 }
1163
1164 /*
1165 * Helper to directly jump to a known parsed path from ->get_link,
1166 * caller must have taken a reference to path beforehand.
1167 */
nd_jump_link(const struct path * path)1168 int nd_jump_link(const struct path *path)
1169 {
1170 int error = -ELOOP;
1171 struct nameidata *nd = current->nameidata;
1172
1173 if (unlikely(nd->flags & LOOKUP_NO_MAGICLINKS))
1174 goto err;
1175
1176 error = -EXDEV;
1177 if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
1178 if (nd->path.mnt != path->mnt)
1179 goto err;
1180 }
1181 /* Not currently safe for scoped-lookups. */
1182 if (unlikely(nd->flags & LOOKUP_IS_SCOPED))
1183 goto err;
1184
1185 path_put(&nd->path);
1186 nd->path = *path;
1187 nd->inode = nd->path.dentry->d_inode;
1188 nd->state |= ND_JUMPED;
1189 return 0;
1190
1191 err:
1192 path_put(path);
1193 return error;
1194 }
1195
put_link(struct nameidata * nd)1196 static inline void put_link(struct nameidata *nd)
1197 {
1198 struct saved *last = nd->stack + --nd->depth;
1199 do_delayed_call(&last->done);
1200 if (!(nd->flags & LOOKUP_RCU))
1201 path_put(&last->link);
1202 }
1203
1204 static int sysctl_protected_symlinks __read_mostly;
1205 static int sysctl_protected_hardlinks __read_mostly;
1206 static int sysctl_protected_fifos __read_mostly;
1207 static int sysctl_protected_regular __read_mostly;
1208
1209 #ifdef CONFIG_SYSCTL
1210 static const struct ctl_table namei_sysctls[] = {
1211 {
1212 .procname = "protected_symlinks",
1213 .data = &sysctl_protected_symlinks,
1214 .maxlen = sizeof(int),
1215 .mode = 0644,
1216 .proc_handler = proc_dointvec_minmax,
1217 .extra1 = SYSCTL_ZERO,
1218 .extra2 = SYSCTL_ONE,
1219 },
1220 {
1221 .procname = "protected_hardlinks",
1222 .data = &sysctl_protected_hardlinks,
1223 .maxlen = sizeof(int),
1224 .mode = 0644,
1225 .proc_handler = proc_dointvec_minmax,
1226 .extra1 = SYSCTL_ZERO,
1227 .extra2 = SYSCTL_ONE,
1228 },
1229 {
1230 .procname = "protected_fifos",
1231 .data = &sysctl_protected_fifos,
1232 .maxlen = sizeof(int),
1233 .mode = 0644,
1234 .proc_handler = proc_dointvec_minmax,
1235 .extra1 = SYSCTL_ZERO,
1236 .extra2 = SYSCTL_TWO,
1237 },
1238 {
1239 .procname = "protected_regular",
1240 .data = &sysctl_protected_regular,
1241 .maxlen = sizeof(int),
1242 .mode = 0644,
1243 .proc_handler = proc_dointvec_minmax,
1244 .extra1 = SYSCTL_ZERO,
1245 .extra2 = SYSCTL_TWO,
1246 },
1247 };
1248
init_fs_namei_sysctls(void)1249 static int __init init_fs_namei_sysctls(void)
1250 {
1251 register_sysctl_init("fs", namei_sysctls);
1252 return 0;
1253 }
1254 fs_initcall(init_fs_namei_sysctls);
1255
1256 #endif /* CONFIG_SYSCTL */
1257
1258 /**
1259 * may_follow_link - Check symlink following for unsafe situations
1260 * @nd: nameidata pathwalk data
1261 * @inode: Used for idmapping.
1262 *
1263 * In the case of the sysctl_protected_symlinks sysctl being enabled,
1264 * CAP_DAC_OVERRIDE needs to be specifically ignored if the symlink is
1265 * in a sticky world-writable directory. This is to protect privileged
1266 * processes from failing races against path names that may change out
1267 * from under them by way of other users creating malicious symlinks.
1268 * It will permit symlinks to be followed only when outside a sticky
1269 * world-writable directory, or when the uid of the symlink and follower
1270 * match, or when the directory owner matches the symlink's owner.
1271 *
1272 * Returns 0 if following the symlink is allowed, -ve on error.
1273 */
may_follow_link(struct nameidata * nd,const struct inode * inode)1274 static inline int may_follow_link(struct nameidata *nd, const struct inode *inode)
1275 {
1276 struct mnt_idmap *idmap;
1277 vfsuid_t vfsuid;
1278
1279 if (!sysctl_protected_symlinks)
1280 return 0;
1281
1282 idmap = mnt_idmap(nd->path.mnt);
1283 vfsuid = i_uid_into_vfsuid(idmap, inode);
1284 /* Allowed if owner and follower match. */
1285 if (vfsuid_eq_kuid(vfsuid, current_fsuid()))
1286 return 0;
1287
1288 /* Allowed if parent directory not sticky and world-writable. */
1289 if ((nd->dir_mode & (S_ISVTX|S_IWOTH)) != (S_ISVTX|S_IWOTH))
1290 return 0;
1291
1292 /* Allowed if parent directory and link owner match. */
1293 if (vfsuid_valid(nd->dir_vfsuid) && vfsuid_eq(nd->dir_vfsuid, vfsuid))
1294 return 0;
1295
1296 if (nd->flags & LOOKUP_RCU)
1297 return -ECHILD;
1298
1299 audit_inode(nd->name, nd->stack[0].link.dentry, 0);
1300 audit_log_path_denied(AUDIT_ANOM_LINK, "follow_link");
1301 return -EACCES;
1302 }
1303
1304 /**
1305 * safe_hardlink_source - Check for safe hardlink conditions
1306 * @idmap: idmap of the mount the inode was found from
1307 * @inode: the source inode to hardlink from
1308 *
1309 * Return false if at least one of the following conditions:
1310 * - inode is not a regular file
1311 * - inode is setuid
1312 * - inode is setgid and group-exec
1313 * - access failure for read and write
1314 *
1315 * Otherwise returns true.
1316 */
safe_hardlink_source(struct mnt_idmap * idmap,struct inode * inode)1317 static bool safe_hardlink_source(struct mnt_idmap *idmap,
1318 struct inode *inode)
1319 {
1320 umode_t mode = inode->i_mode;
1321
1322 /* Special files should not get pinned to the filesystem. */
1323 if (!S_ISREG(mode))
1324 return false;
1325
1326 /* Setuid files should not get pinned to the filesystem. */
1327 if (mode & S_ISUID)
1328 return false;
1329
1330 /* Executable setgid files should not get pinned to the filesystem. */
1331 if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
1332 return false;
1333
1334 /* Hardlinking to unreadable or unwritable sources is dangerous. */
1335 if (inode_permission(idmap, inode, MAY_READ | MAY_WRITE))
1336 return false;
1337
1338 return true;
1339 }
1340
1341 /**
1342 * may_linkat - Check permissions for creating a hardlink
1343 * @idmap: idmap of the mount the inode was found from
1344 * @link: the source to hardlink from
1345 *
1346 * Block hardlink when all of:
1347 * - sysctl_protected_hardlinks enabled
1348 * - fsuid does not match inode
1349 * - hardlink source is unsafe (see safe_hardlink_source() above)
1350 * - not CAP_FOWNER in a namespace with the inode owner uid mapped
1351 *
1352 * If the inode has been found through an idmapped mount the idmap of
1353 * the vfsmount must be passed through @idmap. This function will then take
1354 * care to map the inode according to @idmap before checking permissions.
1355 * On non-idmapped mounts or if permission checking is to be performed on the
1356 * raw inode simply pass @nop_mnt_idmap.
1357 *
1358 * Returns 0 if successful, -ve on error.
1359 */
may_linkat(struct mnt_idmap * idmap,const struct path * link)1360 int may_linkat(struct mnt_idmap *idmap, const struct path *link)
1361 {
1362 struct inode *inode = link->dentry->d_inode;
1363
1364 /* Inode writeback is not safe when the uid or gid are invalid. */
1365 if (!vfsuid_valid(i_uid_into_vfsuid(idmap, inode)) ||
1366 !vfsgid_valid(i_gid_into_vfsgid(idmap, inode)))
1367 return -EOVERFLOW;
1368
1369 if (!sysctl_protected_hardlinks)
1370 return 0;
1371
1372 /* Source inode owner (or CAP_FOWNER) can hardlink all they like,
1373 * otherwise, it must be a safe source.
1374 */
1375 if (safe_hardlink_source(idmap, inode) ||
1376 inode_owner_or_capable(idmap, inode))
1377 return 0;
1378
1379 audit_log_path_denied(AUDIT_ANOM_LINK, "linkat");
1380 return -EPERM;
1381 }
1382
1383 /**
1384 * may_create_in_sticky - Check whether an O_CREAT open in a sticky directory
1385 * should be allowed, or not, on files that already
1386 * exist.
1387 * @idmap: idmap of the mount the inode was found from
1388 * @nd: nameidata pathwalk data
1389 * @inode: the inode of the file to open
1390 *
1391 * Block an O_CREAT open of a FIFO (or a regular file) when:
1392 * - sysctl_protected_fifos (or sysctl_protected_regular) is enabled
1393 * - the file already exists
1394 * - we are in a sticky directory
1395 * - we don't own the file
1396 * - the owner of the directory doesn't own the file
1397 * - the directory is world writable
1398 * If the sysctl_protected_fifos (or sysctl_protected_regular) is set to 2
1399 * the directory doesn't have to be world writable: being group writable will
1400 * be enough.
1401 *
1402 * If the inode has been found through an idmapped mount the idmap of
1403 * the vfsmount must be passed through @idmap. This function will then take
1404 * care to map the inode according to @idmap before checking permissions.
1405 * On non-idmapped mounts or if permission checking is to be performed on the
1406 * raw inode simply pass @nop_mnt_idmap.
1407 *
1408 * Returns 0 if the open is allowed, -ve on error.
1409 */
may_create_in_sticky(struct mnt_idmap * idmap,struct nameidata * nd,struct inode * const inode)1410 static int may_create_in_sticky(struct mnt_idmap *idmap, struct nameidata *nd,
1411 struct inode *const inode)
1412 {
1413 umode_t dir_mode = nd->dir_mode;
1414 vfsuid_t dir_vfsuid = nd->dir_vfsuid, i_vfsuid;
1415
1416 if (likely(!(dir_mode & S_ISVTX)))
1417 return 0;
1418
1419 if (S_ISREG(inode->i_mode) && !sysctl_protected_regular)
1420 return 0;
1421
1422 if (S_ISFIFO(inode->i_mode) && !sysctl_protected_fifos)
1423 return 0;
1424
1425 i_vfsuid = i_uid_into_vfsuid(idmap, inode);
1426
1427 if (vfsuid_eq(i_vfsuid, dir_vfsuid))
1428 return 0;
1429
1430 if (vfsuid_eq_kuid(i_vfsuid, current_fsuid()))
1431 return 0;
1432
1433 if (likely(dir_mode & 0002)) {
1434 audit_log_path_denied(AUDIT_ANOM_CREAT, "sticky_create");
1435 return -EACCES;
1436 }
1437
1438 if (dir_mode & 0020) {
1439 if (sysctl_protected_fifos >= 2 && S_ISFIFO(inode->i_mode)) {
1440 audit_log_path_denied(AUDIT_ANOM_CREAT,
1441 "sticky_create_fifo");
1442 return -EACCES;
1443 }
1444
1445 if (sysctl_protected_regular >= 2 && S_ISREG(inode->i_mode)) {
1446 audit_log_path_denied(AUDIT_ANOM_CREAT,
1447 "sticky_create_regular");
1448 return -EACCES;
1449 }
1450 }
1451
1452 return 0;
1453 }
1454
1455 /*
1456 * follow_up - Find the mountpoint of path's vfsmount
1457 *
1458 * Given a path, find the mountpoint of its source file system.
1459 * Replace @path with the path of the mountpoint in the parent mount.
1460 * Up is towards /.
1461 *
1462 * Return 1 if we went up a level and 0 if we were already at the
1463 * root.
1464 */
follow_up(struct path * path)1465 int follow_up(struct path *path)
1466 {
1467 struct mount *mnt = real_mount(path->mnt);
1468 struct mount *parent;
1469 struct dentry *mountpoint;
1470
1471 read_seqlock_excl(&mount_lock);
1472 parent = mnt->mnt_parent;
1473 if (parent == mnt) {
1474 read_sequnlock_excl(&mount_lock);
1475 return 0;
1476 }
1477 mntget(&parent->mnt);
1478 mountpoint = dget(mnt->mnt_mountpoint);
1479 read_sequnlock_excl(&mount_lock);
1480 dput(path->dentry);
1481 path->dentry = mountpoint;
1482 mntput(path->mnt);
1483 path->mnt = &parent->mnt;
1484 return 1;
1485 }
1486 EXPORT_SYMBOL(follow_up);
1487
choose_mountpoint_rcu(struct mount * m,const struct path * root,struct path * path,unsigned * seqp)1488 static bool choose_mountpoint_rcu(struct mount *m, const struct path *root,
1489 struct path *path, unsigned *seqp)
1490 {
1491 while (mnt_has_parent(m)) {
1492 struct dentry *mountpoint = m->mnt_mountpoint;
1493
1494 m = m->mnt_parent;
1495 if (unlikely(root->dentry == mountpoint &&
1496 root->mnt == &m->mnt))
1497 break;
1498 if (mountpoint != m->mnt.mnt_root) {
1499 path->mnt = &m->mnt;
1500 path->dentry = mountpoint;
1501 *seqp = read_seqcount_begin(&mountpoint->d_seq);
1502 return true;
1503 }
1504 }
1505 return false;
1506 }
1507
choose_mountpoint(struct mount * m,const struct path * root,struct path * path)1508 static bool choose_mountpoint(struct mount *m, const struct path *root,
1509 struct path *path)
1510 {
1511 bool found;
1512
1513 rcu_read_lock();
1514 while (1) {
1515 unsigned seq, mseq = read_seqbegin(&mount_lock);
1516
1517 found = choose_mountpoint_rcu(m, root, path, &seq);
1518 if (unlikely(!found)) {
1519 if (!read_seqretry(&mount_lock, mseq))
1520 break;
1521 } else {
1522 if (likely(__legitimize_path(path, seq, mseq)))
1523 break;
1524 rcu_read_unlock();
1525 path_put(path);
1526 rcu_read_lock();
1527 }
1528 }
1529 rcu_read_unlock();
1530 return found;
1531 }
1532
1533 /*
1534 * Perform an automount
1535 * - return -EISDIR to tell follow_managed() to stop and return the path we
1536 * were called with.
1537 */
follow_automount(struct path * path,int * count,unsigned lookup_flags)1538 static int follow_automount(struct path *path, int *count, unsigned lookup_flags)
1539 {
1540 struct dentry *dentry = path->dentry;
1541
1542 /* We don't want to mount if someone's just doing a stat -
1543 * unless they're stat'ing a directory and appended a '/' to
1544 * the name.
1545 *
1546 * We do, however, want to mount if someone wants to open or
1547 * create a file of any type under the mountpoint, wants to
1548 * traverse through the mountpoint or wants to open the
1549 * mounted directory. Also, autofs may mark negative dentries
1550 * as being automount points. These will need the attentions
1551 * of the daemon to instantiate them before they can be used.
1552 */
1553 if (!(lookup_flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY |
1554 LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) &&
1555 dentry->d_inode)
1556 return -EISDIR;
1557
1558 /* No need to trigger automounts if mountpoint crossing is disabled. */
1559 if (lookup_flags & LOOKUP_NO_XDEV)
1560 return -EXDEV;
1561
1562 if (count && (*count)++ >= MAXSYMLINKS)
1563 return -ELOOP;
1564
1565 return finish_automount(dentry->d_op->d_automount(path), path);
1566 }
1567
1568 /*
1569 * mount traversal - out-of-line part. One note on ->d_flags accesses -
1570 * dentries are pinned but not locked here, so negative dentry can go
1571 * positive right under us. Use of smp_load_acquire() provides a barrier
1572 * sufficient for ->d_inode and ->d_flags consistency.
1573 */
__traverse_mounts(struct path * path,unsigned flags,bool * jumped,int * count,unsigned lookup_flags)1574 static int __traverse_mounts(struct path *path, unsigned flags, bool *jumped,
1575 int *count, unsigned lookup_flags)
1576 {
1577 struct vfsmount *mnt = path->mnt;
1578 bool need_mntput = false;
1579 int ret = 0;
1580
1581 while (flags & DCACHE_MANAGED_DENTRY) {
1582 /* Allow the filesystem to manage the transit without i_rwsem
1583 * being held. */
1584 if (flags & DCACHE_MANAGE_TRANSIT) {
1585 if (lookup_flags & LOOKUP_NO_XDEV) {
1586 ret = -EXDEV;
1587 break;
1588 }
1589 ret = path->dentry->d_op->d_manage(path, false);
1590 flags = smp_load_acquire(&path->dentry->d_flags);
1591 if (ret < 0)
1592 break;
1593 }
1594
1595 if (flags & DCACHE_MOUNTED) { // something's mounted on it..
1596 struct vfsmount *mounted = lookup_mnt(path);
1597 if (mounted) { // ... in our namespace
1598 dput(path->dentry);
1599 if (need_mntput)
1600 mntput(path->mnt);
1601 path->mnt = mounted;
1602 path->dentry = dget(mounted->mnt_root);
1603 // here we know it's positive
1604 flags = path->dentry->d_flags;
1605 need_mntput = true;
1606 if (unlikely(lookup_flags & LOOKUP_NO_XDEV)) {
1607 ret = -EXDEV;
1608 break;
1609 }
1610 continue;
1611 }
1612 }
1613
1614 if (!(flags & DCACHE_NEED_AUTOMOUNT))
1615 break;
1616
1617 // uncovered automount point
1618 ret = follow_automount(path, count, lookup_flags);
1619 flags = smp_load_acquire(&path->dentry->d_flags);
1620 if (ret < 0)
1621 break;
1622 }
1623
1624 if (ret == -EISDIR)
1625 ret = 0;
1626 // possible if you race with several mount --move
1627 if (need_mntput && path->mnt == mnt)
1628 mntput(path->mnt);
1629 if (!ret && unlikely(d_flags_negative(flags)))
1630 ret = -ENOENT;
1631 *jumped = need_mntput;
1632 return ret;
1633 }
1634
traverse_mounts(struct path * path,bool * jumped,int * count,unsigned lookup_flags)1635 static inline int traverse_mounts(struct path *path, bool *jumped,
1636 int *count, unsigned lookup_flags)
1637 {
1638 unsigned flags = smp_load_acquire(&path->dentry->d_flags);
1639
1640 /* fastpath */
1641 if (likely(!(flags & DCACHE_MANAGED_DENTRY))) {
1642 *jumped = false;
1643 if (unlikely(d_flags_negative(flags)))
1644 return -ENOENT;
1645 return 0;
1646 }
1647 return __traverse_mounts(path, flags, jumped, count, lookup_flags);
1648 }
1649
follow_down_one(struct path * path)1650 int follow_down_one(struct path *path)
1651 {
1652 struct vfsmount *mounted;
1653
1654 mounted = lookup_mnt(path);
1655 if (mounted) {
1656 dput(path->dentry);
1657 mntput(path->mnt);
1658 path->mnt = mounted;
1659 path->dentry = dget(mounted->mnt_root);
1660 return 1;
1661 }
1662 return 0;
1663 }
1664 EXPORT_SYMBOL(follow_down_one);
1665
1666 /*
1667 * Follow down to the covering mount currently visible to userspace. At each
1668 * point, the filesystem owning that dentry may be queried as to whether the
1669 * caller is permitted to proceed or not.
1670 */
follow_down(struct path * path,unsigned int flags)1671 int follow_down(struct path *path, unsigned int flags)
1672 {
1673 struct vfsmount *mnt = path->mnt;
1674 bool jumped;
1675 int ret = traverse_mounts(path, &jumped, NULL, flags);
1676
1677 if (path->mnt != mnt)
1678 mntput(mnt);
1679 return ret;
1680 }
1681 EXPORT_SYMBOL(follow_down);
1682
1683 /*
1684 * Try to skip to top of mountpoint pile in rcuwalk mode. Fail if
1685 * we meet a managed dentry that would need blocking.
1686 */
__follow_mount_rcu(struct nameidata * nd,struct path * path)1687 static bool __follow_mount_rcu(struct nameidata *nd, struct path *path)
1688 {
1689 struct dentry *dentry = path->dentry;
1690 unsigned int flags = dentry->d_flags;
1691
1692 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
1693 return false;
1694
1695 for (;;) {
1696 /*
1697 * Don't forget we might have a non-mountpoint managed dentry
1698 * that wants to block transit.
1699 */
1700 if (unlikely(flags & DCACHE_MANAGE_TRANSIT)) {
1701 int res = dentry->d_op->d_manage(path, true);
1702 if (res)
1703 return res == -EISDIR;
1704 flags = dentry->d_flags;
1705 }
1706
1707 if (flags & DCACHE_MOUNTED) {
1708 struct mount *mounted = __lookup_mnt(path->mnt, dentry);
1709 if (mounted) {
1710 path->mnt = &mounted->mnt;
1711 dentry = path->dentry = mounted->mnt.mnt_root;
1712 nd->state |= ND_JUMPED;
1713 nd->next_seq = read_seqcount_begin(&dentry->d_seq);
1714 flags = dentry->d_flags;
1715 // makes sure that non-RCU pathwalk could reach
1716 // this state.
1717 if (read_seqretry(&mount_lock, nd->m_seq))
1718 return false;
1719 continue;
1720 }
1721 if (read_seqretry(&mount_lock, nd->m_seq))
1722 return false;
1723 }
1724 return !(flags & DCACHE_NEED_AUTOMOUNT);
1725 }
1726 }
1727
handle_mounts(struct nameidata * nd,struct dentry * dentry,struct path * path)1728 static inline int handle_mounts(struct nameidata *nd, struct dentry *dentry,
1729 struct path *path)
1730 {
1731 bool jumped;
1732 int ret;
1733
1734 path->mnt = nd->path.mnt;
1735 path->dentry = dentry;
1736 if (nd->flags & LOOKUP_RCU) {
1737 unsigned int seq = nd->next_seq;
1738 if (likely(!d_managed(dentry)))
1739 return 0;
1740 if (likely(__follow_mount_rcu(nd, path)))
1741 return 0;
1742 // *path and nd->next_seq might've been clobbered
1743 path->mnt = nd->path.mnt;
1744 path->dentry = dentry;
1745 nd->next_seq = seq;
1746 if (unlikely(!try_to_unlazy_next(nd, dentry)))
1747 return -ECHILD;
1748 }
1749 ret = traverse_mounts(path, &jumped, &nd->total_link_count, nd->flags);
1750 if (jumped)
1751 nd->state |= ND_JUMPED;
1752 if (unlikely(ret)) {
1753 dput(path->dentry);
1754 if (path->mnt != nd->path.mnt)
1755 mntput(path->mnt);
1756 }
1757 return ret;
1758 }
1759
1760 /*
1761 * This looks up the name in dcache and possibly revalidates the found dentry.
1762 * NULL is returned if the dentry does not exist in the cache.
1763 */
lookup_dcache(const struct qstr * name,struct dentry * dir,unsigned int flags)1764 static struct dentry *lookup_dcache(const struct qstr *name,
1765 struct dentry *dir,
1766 unsigned int flags)
1767 {
1768 struct dentry *dentry = d_lookup(dir, name);
1769 if (dentry) {
1770 int error = d_revalidate(dir->d_inode, name, dentry, flags);
1771 if (unlikely(error <= 0)) {
1772 if (!error)
1773 d_invalidate(dentry);
1774 dput(dentry);
1775 return ERR_PTR(error);
1776 }
1777 }
1778 return dentry;
1779 }
1780
1781 /*
1782 * Parent directory has inode locked exclusive. This is one
1783 * and only case when ->lookup() gets called on non in-lookup
1784 * dentries - as the matter of fact, this only gets called
1785 * when directory is guaranteed to have no in-lookup children
1786 * at all.
1787 * Will return -ENOENT if name isn't found and LOOKUP_CREATE wasn't passed.
1788 * Will return -EEXIST if name is found and LOOKUP_EXCL was passed.
1789 */
lookup_one_qstr_excl(const struct qstr * name,struct dentry * base,unsigned int flags)1790 static struct dentry *lookup_one_qstr_excl(const struct qstr *name,
1791 struct dentry *base, unsigned int flags)
1792 {
1793 struct dentry *dentry;
1794 struct dentry *old;
1795 struct inode *dir;
1796
1797 dentry = lookup_dcache(name, base, flags);
1798 if (dentry)
1799 goto found;
1800
1801 /* Don't create child dentry for a dead directory. */
1802 dir = base->d_inode;
1803 if (unlikely(IS_DEADDIR(dir)))
1804 return ERR_PTR(-ENOENT);
1805
1806 dentry = d_alloc(base, name);
1807 if (unlikely(!dentry))
1808 return ERR_PTR(-ENOMEM);
1809
1810 old = dir->i_op->lookup(dir, dentry, flags);
1811 if (unlikely(old)) {
1812 dput(dentry);
1813 dentry = old;
1814 }
1815 found:
1816 if (IS_ERR(dentry))
1817 return dentry;
1818 if (d_is_negative(dentry) && !(flags & LOOKUP_CREATE)) {
1819 dput(dentry);
1820 return ERR_PTR(-ENOENT);
1821 }
1822 if (d_is_positive(dentry) && (flags & LOOKUP_EXCL)) {
1823 dput(dentry);
1824 return ERR_PTR(-EEXIST);
1825 }
1826 return dentry;
1827 }
1828
1829 /**
1830 * lookup_fast - do fast lockless (but racy) lookup of a dentry
1831 * @nd: current nameidata
1832 *
1833 * Do a fast, but racy lookup in the dcache for the given dentry, and
1834 * revalidate it. Returns a valid dentry pointer or NULL if one wasn't
1835 * found. On error, an ERR_PTR will be returned.
1836 *
1837 * If this function returns a valid dentry and the walk is no longer
1838 * lazy, the dentry will carry a reference that must later be put. If
1839 * RCU mode is still in force, then this is not the case and the dentry
1840 * must be legitimized before use. If this returns NULL, then the walk
1841 * will no longer be in RCU mode.
1842 */
lookup_fast(struct nameidata * nd)1843 static struct dentry *lookup_fast(struct nameidata *nd)
1844 {
1845 struct dentry *dentry, *parent = nd->path.dentry;
1846 int status = 1;
1847
1848 /*
1849 * Rename seqlock is not required here because in the off chance
1850 * of a false negative due to a concurrent rename, the caller is
1851 * going to fall back to non-racy lookup.
1852 */
1853 if (nd->flags & LOOKUP_RCU) {
1854 dentry = __d_lookup_rcu(parent, &nd->last, &nd->next_seq);
1855 if (unlikely(!dentry)) {
1856 if (!try_to_unlazy(nd))
1857 return ERR_PTR(-ECHILD);
1858 return NULL;
1859 }
1860
1861 /*
1862 * This sequence count validates that the parent had no
1863 * changes while we did the lookup of the dentry above.
1864 */
1865 if (read_seqcount_retry(&parent->d_seq, nd->seq))
1866 return ERR_PTR(-ECHILD);
1867
1868 status = d_revalidate(nd->inode, &nd->last, dentry, nd->flags);
1869 if (likely(status > 0))
1870 return dentry;
1871 if (!try_to_unlazy_next(nd, dentry))
1872 return ERR_PTR(-ECHILD);
1873 if (status == -ECHILD)
1874 /* we'd been told to redo it in non-rcu mode */
1875 status = d_revalidate(nd->inode, &nd->last,
1876 dentry, nd->flags);
1877 } else {
1878 dentry = __d_lookup(parent, &nd->last);
1879 if (unlikely(!dentry))
1880 return NULL;
1881 status = d_revalidate(nd->inode, &nd->last, dentry, nd->flags);
1882 }
1883 if (unlikely(status <= 0)) {
1884 if (!status)
1885 d_invalidate(dentry);
1886 dput(dentry);
1887 return ERR_PTR(status);
1888 }
1889 return dentry;
1890 }
1891
1892 /* Fast lookup failed, do it the slow way */
__lookup_slow(const struct qstr * name,struct dentry * dir,unsigned int flags)1893 static struct dentry *__lookup_slow(const struct qstr *name,
1894 struct dentry *dir,
1895 unsigned int flags)
1896 {
1897 struct dentry *dentry, *old;
1898 struct inode *inode = dir->d_inode;
1899
1900 /* Don't go there if it's already dead */
1901 if (unlikely(IS_DEADDIR(inode)))
1902 return ERR_PTR(-ENOENT);
1903 again:
1904 dentry = d_alloc_parallel(dir, name);
1905 if (IS_ERR(dentry))
1906 return dentry;
1907 if (unlikely(!d_in_lookup(dentry))) {
1908 int error = d_revalidate(inode, name, dentry, flags);
1909 if (unlikely(error <= 0)) {
1910 if (!error) {
1911 d_invalidate(dentry);
1912 dput(dentry);
1913 goto again;
1914 }
1915 dput(dentry);
1916 dentry = ERR_PTR(error);
1917 }
1918 } else {
1919 old = inode->i_op->lookup(inode, dentry, flags);
1920 d_lookup_done(dentry);
1921 if (unlikely(old)) {
1922 dput(dentry);
1923 dentry = old;
1924 }
1925 }
1926 return dentry;
1927 }
1928
lookup_slow(const struct qstr * name,struct dentry * dir,unsigned int flags)1929 static noinline struct dentry *lookup_slow(const struct qstr *name,
1930 struct dentry *dir,
1931 unsigned int flags)
1932 {
1933 struct inode *inode = dir->d_inode;
1934 struct dentry *res;
1935 inode_lock_shared(inode);
1936 res = __lookup_slow(name, dir, flags);
1937 inode_unlock_shared(inode);
1938 return res;
1939 }
1940
lookup_slow_killable(const struct qstr * name,struct dentry * dir,unsigned int flags)1941 static struct dentry *lookup_slow_killable(const struct qstr *name,
1942 struct dentry *dir,
1943 unsigned int flags)
1944 {
1945 struct inode *inode = dir->d_inode;
1946 struct dentry *res;
1947
1948 if (inode_lock_shared_killable(inode))
1949 return ERR_PTR(-EINTR);
1950 res = __lookup_slow(name, dir, flags);
1951 inode_unlock_shared(inode);
1952 return res;
1953 }
1954
may_lookup(struct mnt_idmap * idmap,struct nameidata * restrict nd)1955 static inline int may_lookup(struct mnt_idmap *idmap,
1956 struct nameidata *restrict nd)
1957 {
1958 int err, mask;
1959
1960 mask = nd->flags & LOOKUP_RCU ? MAY_NOT_BLOCK : 0;
1961 err = lookup_inode_permission_may_exec(idmap, nd->inode, mask);
1962 if (likely(!err))
1963 return 0;
1964
1965 // If we failed, and we weren't in LOOKUP_RCU, it's final
1966 if (!(nd->flags & LOOKUP_RCU))
1967 return err;
1968
1969 // Drop out of RCU mode to make sure it wasn't transient
1970 if (!try_to_unlazy(nd))
1971 return -ECHILD; // redo it all non-lazy
1972
1973 if (err != -ECHILD) // hard error
1974 return err;
1975
1976 return lookup_inode_permission_may_exec(idmap, nd->inode, 0);
1977 }
1978
reserve_stack(struct nameidata * nd,struct path * link)1979 static int reserve_stack(struct nameidata *nd, struct path *link)
1980 {
1981 if (unlikely(nd->total_link_count++ >= MAXSYMLINKS))
1982 return -ELOOP;
1983
1984 if (likely(nd->depth != EMBEDDED_LEVELS))
1985 return 0;
1986 if (likely(nd->stack != nd->internal))
1987 return 0;
1988 if (likely(nd_alloc_stack(nd)))
1989 return 0;
1990
1991 if (nd->flags & LOOKUP_RCU) {
1992 // we need to grab link before we do unlazy. And we can't skip
1993 // unlazy even if we fail to grab the link - cleanup needs it
1994 bool grabbed_link = legitimize_path(nd, link, nd->next_seq);
1995
1996 if (!try_to_unlazy(nd) || !grabbed_link)
1997 return -ECHILD;
1998
1999 if (nd_alloc_stack(nd))
2000 return 0;
2001 }
2002 return -ENOMEM;
2003 }
2004
2005 enum {WALK_TRAILING = 1, WALK_MORE = 2, WALK_NOFOLLOW = 4};
2006
pick_link(struct nameidata * nd,struct path * link,struct inode * inode,int flags)2007 static noinline const char *pick_link(struct nameidata *nd, struct path *link,
2008 struct inode *inode, int flags)
2009 {
2010 struct saved *last;
2011 const char *res;
2012 int error;
2013
2014 if (nd->flags & LOOKUP_RCU) {
2015 /* make sure that d_is_symlink from step_into_slowpath() matches the inode */
2016 if (read_seqcount_retry(&link->dentry->d_seq, nd->next_seq))
2017 return ERR_PTR(-ECHILD);
2018 } else {
2019 if (link->mnt == nd->path.mnt)
2020 mntget(link->mnt);
2021 }
2022
2023 error = reserve_stack(nd, link);
2024 if (unlikely(error)) {
2025 if (!(nd->flags & LOOKUP_RCU))
2026 path_put(link);
2027 return ERR_PTR(error);
2028 }
2029 last = nd->stack + nd->depth++;
2030 last->link = *link;
2031 clear_delayed_call(&last->done);
2032 last->seq = nd->next_seq;
2033
2034 if (flags & WALK_TRAILING) {
2035 error = may_follow_link(nd, inode);
2036 if (unlikely(error))
2037 return ERR_PTR(error);
2038 }
2039
2040 if (unlikely(nd->flags & LOOKUP_NO_SYMLINKS) ||
2041 unlikely(link->mnt->mnt_flags & MNT_NOSYMFOLLOW))
2042 return ERR_PTR(-ELOOP);
2043
2044 if (unlikely(atime_needs_update(&last->link, inode))) {
2045 if (nd->flags & LOOKUP_RCU) {
2046 if (!try_to_unlazy(nd))
2047 return ERR_PTR(-ECHILD);
2048 }
2049 touch_atime(&last->link);
2050 cond_resched();
2051 }
2052
2053 error = security_inode_follow_link(link->dentry, inode,
2054 nd->flags & LOOKUP_RCU);
2055 if (unlikely(error))
2056 return ERR_PTR(error);
2057
2058 res = READ_ONCE(inode->i_link);
2059 if (!res) {
2060 const char * (*get)(struct dentry *, struct inode *,
2061 struct delayed_call *);
2062 get = inode->i_op->get_link;
2063 if (nd->flags & LOOKUP_RCU) {
2064 res = get(NULL, inode, &last->done);
2065 if (res == ERR_PTR(-ECHILD) && try_to_unlazy(nd))
2066 res = get(link->dentry, inode, &last->done);
2067 } else {
2068 res = get(link->dentry, inode, &last->done);
2069 }
2070 if (!res)
2071 goto all_done;
2072 if (IS_ERR(res))
2073 return res;
2074 }
2075 if (*res == '/') {
2076 error = nd_jump_root(nd);
2077 if (unlikely(error))
2078 return ERR_PTR(error);
2079 while (unlikely(*++res == '/'))
2080 ;
2081 }
2082 if (*res)
2083 return res;
2084 all_done: // pure jump
2085 put_link(nd);
2086 return NULL;
2087 }
2088
2089 /*
2090 * Do we need to follow links? We _really_ want to be able
2091 * to do this check without having to look at inode->i_op,
2092 * so we keep a cache of "no, this doesn't need follow_link"
2093 * for the common case.
2094 *
2095 * NOTE: dentry must be what nd->next_seq had been sampled from.
2096 */
step_into_slowpath(struct nameidata * nd,int flags,struct dentry * dentry)2097 static noinline const char *step_into_slowpath(struct nameidata *nd, int flags,
2098 struct dentry *dentry)
2099 {
2100 struct path path;
2101 struct inode *inode;
2102 int err;
2103
2104 err = handle_mounts(nd, dentry, &path);
2105 if (unlikely(err < 0))
2106 return ERR_PTR(err);
2107 inode = path.dentry->d_inode;
2108 if (likely(!d_is_symlink(path.dentry)) ||
2109 ((flags & WALK_TRAILING) && !(nd->flags & LOOKUP_FOLLOW)) ||
2110 (flags & WALK_NOFOLLOW)) {
2111 /* not a symlink or should not follow */
2112 if (nd->flags & LOOKUP_RCU) {
2113 if (read_seqcount_retry(&path.dentry->d_seq, nd->next_seq))
2114 return ERR_PTR(-ECHILD);
2115 if (unlikely(!inode))
2116 return ERR_PTR(-ENOENT);
2117 } else {
2118 dput(nd->path.dentry);
2119 if (nd->path.mnt != path.mnt)
2120 mntput(nd->path.mnt);
2121 }
2122 nd->path = path;
2123 nd->inode = inode;
2124 nd->seq = nd->next_seq;
2125 return NULL;
2126 }
2127 return pick_link(nd, &path, inode, flags);
2128 }
2129
step_into(struct nameidata * nd,int flags,struct dentry * dentry)2130 static __always_inline const char *step_into(struct nameidata *nd, int flags,
2131 struct dentry *dentry)
2132 {
2133 /*
2134 * In the common case we are in rcu-walk and traversing over a non-mounted on
2135 * directory (as opposed to e.g., a symlink).
2136 *
2137 * We can handle that and negative entries with the checks below.
2138 */
2139 if (likely((nd->flags & LOOKUP_RCU) &&
2140 !d_managed(dentry) && !d_is_symlink(dentry))) {
2141 struct inode *inode = dentry->d_inode;
2142 if (read_seqcount_retry(&dentry->d_seq, nd->next_seq))
2143 return ERR_PTR(-ECHILD);
2144 if (unlikely(!inode))
2145 return ERR_PTR(-ENOENT);
2146 nd->path.dentry = dentry;
2147 /* nd->path.mnt remains unchanged as no mount point was crossed */
2148 nd->inode = inode;
2149 nd->seq = nd->next_seq;
2150 return NULL;
2151 }
2152 return step_into_slowpath(nd, flags, dentry);
2153 }
2154
follow_dotdot_rcu(struct nameidata * nd)2155 static struct dentry *follow_dotdot_rcu(struct nameidata *nd)
2156 {
2157 struct dentry *parent, *old;
2158
2159 if (path_equal(&nd->path, &nd->root))
2160 goto in_root;
2161 if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
2162 struct path path;
2163 unsigned seq;
2164 if (!choose_mountpoint_rcu(real_mount(nd->path.mnt),
2165 &nd->root, &path, &seq))
2166 goto in_root;
2167 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
2168 return ERR_PTR(-ECHILD);
2169 nd->path = path;
2170 nd->inode = path.dentry->d_inode;
2171 nd->seq = seq;
2172 // makes sure that non-RCU pathwalk could reach this state
2173 if (read_seqretry(&mount_lock, nd->m_seq))
2174 return ERR_PTR(-ECHILD);
2175 /* we know that mountpoint was pinned */
2176 }
2177 old = nd->path.dentry;
2178 parent = old->d_parent;
2179 nd->next_seq = read_seqcount_begin(&parent->d_seq);
2180 // makes sure that non-RCU pathwalk could reach this state
2181 if (read_seqcount_retry(&old->d_seq, nd->seq))
2182 return ERR_PTR(-ECHILD);
2183 if (unlikely(!path_connected(nd->path.mnt, parent)))
2184 return ERR_PTR(-ECHILD);
2185 return parent;
2186 in_root:
2187 if (read_seqretry(&mount_lock, nd->m_seq))
2188 return ERR_PTR(-ECHILD);
2189 if (unlikely(nd->flags & LOOKUP_BENEATH))
2190 return ERR_PTR(-ECHILD);
2191 nd->next_seq = nd->seq;
2192 return nd->path.dentry;
2193 }
2194
follow_dotdot(struct nameidata * nd)2195 static struct dentry *follow_dotdot(struct nameidata *nd)
2196 {
2197 struct dentry *parent;
2198
2199 if (path_equal(&nd->path, &nd->root))
2200 goto in_root;
2201 if (unlikely(nd->path.dentry == nd->path.mnt->mnt_root)) {
2202 struct path path;
2203
2204 if (!choose_mountpoint(real_mount(nd->path.mnt),
2205 &nd->root, &path))
2206 goto in_root;
2207 path_put(&nd->path);
2208 nd->path = path;
2209 nd->inode = path.dentry->d_inode;
2210 if (unlikely(nd->flags & LOOKUP_NO_XDEV))
2211 return ERR_PTR(-EXDEV);
2212 }
2213 /* rare case of legitimate dget_parent()... */
2214 parent = dget_parent(nd->path.dentry);
2215 if (unlikely(!path_connected(nd->path.mnt, parent))) {
2216 dput(parent);
2217 return ERR_PTR(-ENOENT);
2218 }
2219 return parent;
2220
2221 in_root:
2222 if (unlikely(nd->flags & LOOKUP_BENEATH))
2223 return ERR_PTR(-EXDEV);
2224 return dget(nd->path.dentry);
2225 }
2226
handle_dots(struct nameidata * nd,enum last_type type)2227 static const char *handle_dots(struct nameidata *nd, enum last_type type)
2228 {
2229 if (type == LAST_DOTDOT) {
2230 const char *error = NULL;
2231 struct dentry *parent;
2232
2233 if (!nd->root.mnt) {
2234 error = ERR_PTR(set_root(nd));
2235 if (unlikely(error))
2236 return error;
2237 }
2238 if (nd->flags & LOOKUP_RCU)
2239 parent = follow_dotdot_rcu(nd);
2240 else
2241 parent = follow_dotdot(nd);
2242 if (IS_ERR(parent))
2243 return ERR_CAST(parent);
2244 error = step_into(nd, WALK_NOFOLLOW, parent);
2245 if (unlikely(error))
2246 return error;
2247
2248 if (unlikely(nd->flags & LOOKUP_IS_SCOPED)) {
2249 /*
2250 * If there was a racing rename or mount along our
2251 * path, then we can't be sure that ".." hasn't jumped
2252 * above nd->root (and so userspace should retry or use
2253 * some fallback).
2254 */
2255 smp_rmb();
2256 if (__read_seqcount_retry(&mount_lock.seqcount, nd->m_seq))
2257 return ERR_PTR(-EAGAIN);
2258 if (__read_seqcount_retry(&rename_lock.seqcount, nd->r_seq))
2259 return ERR_PTR(-EAGAIN);
2260 }
2261 }
2262 return NULL;
2263 }
2264
walk_component(struct nameidata * nd,int flags)2265 static __always_inline const char *walk_component(struct nameidata *nd, int flags)
2266 {
2267 struct dentry *dentry;
2268 /*
2269 * "." and ".." are special - ".." especially so because it has
2270 * to be able to know about the current root directory and
2271 * parent relationships.
2272 */
2273 if (unlikely(nd->last_type != LAST_NORM)) {
2274 if (unlikely(nd->depth) && !(flags & WALK_MORE))
2275 put_link(nd);
2276 return handle_dots(nd, nd->last_type);
2277 }
2278 dentry = lookup_fast(nd);
2279 if (IS_ERR(dentry))
2280 return ERR_CAST(dentry);
2281 if (unlikely(!dentry)) {
2282 dentry = lookup_slow(&nd->last, nd->path.dentry, nd->flags);
2283 if (IS_ERR(dentry))
2284 return ERR_CAST(dentry);
2285 }
2286 if (unlikely(nd->depth) && !(flags & WALK_MORE))
2287 put_link(nd);
2288 return step_into(nd, flags, dentry);
2289 }
2290
2291 /*
2292 * We can do the critical dentry name comparison and hashing
2293 * operations one word at a time, but we are limited to:
2294 *
2295 * - Architectures with fast unaligned word accesses. We could
2296 * do a "get_unaligned()" if this helps and is sufficiently
2297 * fast.
2298 *
2299 * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we
2300 * do not trap on the (extremely unlikely) case of a page
2301 * crossing operation.
2302 *
2303 * - Furthermore, we need an efficient 64-bit compile for the
2304 * 64-bit case in order to generate the "number of bytes in
2305 * the final mask". Again, that could be replaced with a
2306 * efficient population count instruction or similar.
2307 */
2308 #ifdef CONFIG_DCACHE_WORD_ACCESS
2309
2310 #include <asm/word-at-a-time.h>
2311
2312 #ifdef HASH_MIX
2313
2314 /* Architecture provides HASH_MIX and fold_hash() in <asm/hash.h> */
2315
2316 #elif defined(CONFIG_64BIT)
2317 /*
2318 * Register pressure in the mixing function is an issue, particularly
2319 * on 32-bit x86, but almost any function requires one state value and
2320 * one temporary. Instead, use a function designed for two state values
2321 * and no temporaries.
2322 *
2323 * This function cannot create a collision in only two iterations, so
2324 * we have two iterations to achieve avalanche. In those two iterations,
2325 * we have six layers of mixing, which is enough to spread one bit's
2326 * influence out to 2^6 = 64 state bits.
2327 *
2328 * Rotate constants are scored by considering either 64 one-bit input
2329 * deltas or 64*63/2 = 2016 two-bit input deltas, and finding the
2330 * probability of that delta causing a change to each of the 128 output
2331 * bits, using a sample of random initial states.
2332 *
2333 * The Shannon entropy of the computed probabilities is then summed
2334 * to produce a score. Ideally, any input change has a 50% chance of
2335 * toggling any given output bit.
2336 *
2337 * Mixing scores (in bits) for (12,45):
2338 * Input delta: 1-bit 2-bit
2339 * 1 round: 713.3 42542.6
2340 * 2 rounds: 2753.7 140389.8
2341 * 3 rounds: 5954.1 233458.2
2342 * 4 rounds: 7862.6 256672.2
2343 * Perfect: 8192 258048
2344 * (64*128) (64*63/2 * 128)
2345 */
2346 #define HASH_MIX(x, y, a) \
2347 ( x ^= (a), \
2348 y ^= x, x = rol64(x,12),\
2349 x += y, y = rol64(y,45),\
2350 y *= 9 )
2351
2352 /*
2353 * Fold two longs into one 32-bit hash value. This must be fast, but
2354 * latency isn't quite as critical, as there is a fair bit of additional
2355 * work done before the hash value is used.
2356 */
fold_hash(unsigned long x,unsigned long y)2357 static inline unsigned int fold_hash(unsigned long x, unsigned long y)
2358 {
2359 y ^= x * GOLDEN_RATIO_64;
2360 y *= GOLDEN_RATIO_64;
2361 return y >> 32;
2362 }
2363
2364 #else /* 32-bit case */
2365
2366 /*
2367 * Mixing scores (in bits) for (7,20):
2368 * Input delta: 1-bit 2-bit
2369 * 1 round: 330.3 9201.6
2370 * 2 rounds: 1246.4 25475.4
2371 * 3 rounds: 1907.1 31295.1
2372 * 4 rounds: 2042.3 31718.6
2373 * Perfect: 2048 31744
2374 * (32*64) (32*31/2 * 64)
2375 */
2376 #define HASH_MIX(x, y, a) \
2377 ( x ^= (a), \
2378 y ^= x, x = rol32(x, 7),\
2379 x += y, y = rol32(y,20),\
2380 y *= 9 )
2381
fold_hash(unsigned long x,unsigned long y)2382 static inline unsigned int fold_hash(unsigned long x, unsigned long y)
2383 {
2384 /* Use arch-optimized multiply if one exists */
2385 return __hash_32(y ^ __hash_32(x));
2386 }
2387
2388 #endif
2389
2390 /*
2391 * Return the hash of a string of known length. This is carfully
2392 * designed to match hash_name(), which is the more critical function.
2393 * In particular, we must end by hashing a final word containing 0..7
2394 * payload bytes, to match the way that hash_name() iterates until it
2395 * finds the delimiter after the name.
2396 */
full_name_hash(const void * salt,const char * name,unsigned int len)2397 unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2398 {
2399 unsigned long a, x = 0, y = (unsigned long)salt;
2400
2401 for (;;) {
2402 if (!len)
2403 goto done;
2404 a = load_unaligned_zeropad(name);
2405 if (len < sizeof(unsigned long))
2406 break;
2407 HASH_MIX(x, y, a);
2408 name += sizeof(unsigned long);
2409 len -= sizeof(unsigned long);
2410 }
2411 x ^= a & bytemask_from_count(len);
2412 done:
2413 return fold_hash(x, y);
2414 }
2415 EXPORT_SYMBOL(full_name_hash);
2416
2417 /* Return the "hash_len" (hash and length) of a null-terminated string */
hashlen_string(const void * salt,const char * name)2418 u64 hashlen_string(const void *salt, const char *name)
2419 {
2420 unsigned long a = 0, x = 0, y = (unsigned long)salt;
2421 unsigned long adata, mask, len;
2422 const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2423
2424 len = 0;
2425 goto inside;
2426
2427 do {
2428 HASH_MIX(x, y, a);
2429 len += sizeof(unsigned long);
2430 inside:
2431 a = load_unaligned_zeropad(name+len);
2432 } while (!has_zero(a, &adata, &constants));
2433
2434 adata = prep_zero_mask(a, adata, &constants);
2435 mask = create_zero_mask(adata);
2436 x ^= a & zero_bytemask(mask);
2437
2438 return hashlen_create(fold_hash(x, y), len + find_zero(mask));
2439 }
2440 EXPORT_SYMBOL(hashlen_string);
2441
2442 /*
2443 * hash_name - Calculate the length and hash of the path component
2444 * @nd: the path resolution state
2445 * @name: the pathname to read the component from
2446 * @lastword: if the component fits in a single word, LAST_WORD_IS_DOT,
2447 * LAST_WORD_IS_DOTDOT, or some other value depending on whether the
2448 * component is '.', '..', or something else. Otherwise, @lastword is 0.
2449 *
2450 * Returns: a pointer to the terminating '/' or NUL character in @name.
2451 */
hash_name(struct nameidata * nd,const char * name,unsigned long * lastword)2452 static inline const char *hash_name(struct nameidata *nd,
2453 const char *name,
2454 unsigned long *lastword)
2455 {
2456 unsigned long a, b, x, y = (unsigned long)nd->path.dentry;
2457 unsigned long adata, bdata, mask, len;
2458 const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
2459
2460 /*
2461 * The first iteration is special, because it can result in
2462 * '.' and '..' and has no mixing other than the final fold.
2463 */
2464 a = load_unaligned_zeropad(name);
2465 b = a ^ REPEAT_BYTE('/');
2466 if (has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)) {
2467 adata = prep_zero_mask(a, adata, &constants);
2468 bdata = prep_zero_mask(b, bdata, &constants);
2469 mask = create_zero_mask(adata | bdata);
2470 a &= zero_bytemask(mask);
2471 *lastword = a;
2472 len = find_zero(mask);
2473 nd->last.hash = fold_hash(a, y);
2474 nd->last.len = len;
2475 return name + len;
2476 }
2477
2478 len = 0;
2479 x = 0;
2480 do {
2481 HASH_MIX(x, y, a);
2482 len += sizeof(unsigned long);
2483 a = load_unaligned_zeropad(name+len);
2484 b = a ^ REPEAT_BYTE('/');
2485 } while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)));
2486
2487 adata = prep_zero_mask(a, adata, &constants);
2488 bdata = prep_zero_mask(b, bdata, &constants);
2489 mask = create_zero_mask(adata | bdata);
2490 a &= zero_bytemask(mask);
2491 x ^= a;
2492 len += find_zero(mask);
2493 *lastword = 0; // Multi-word components cannot be DOT or DOTDOT
2494
2495 nd->last.hash = fold_hash(x, y);
2496 nd->last.len = len;
2497 return name + len;
2498 }
2499
2500 /*
2501 * Note that the 'last' word is always zero-masked, but
2502 * was loaded as a possibly big-endian word.
2503 */
2504 #ifdef __BIG_ENDIAN
2505 #define LAST_WORD_IS_DOT (0x2eul << (BITS_PER_LONG-8))
2506 #define LAST_WORD_IS_DOTDOT (0x2e2eul << (BITS_PER_LONG-16))
2507 #endif
2508
2509 #else /* !CONFIG_DCACHE_WORD_ACCESS: Slow, byte-at-a-time version */
2510
2511 /* Return the hash of a string of known length */
full_name_hash(const void * salt,const char * name,unsigned int len)2512 unsigned int full_name_hash(const void *salt, const char *name, unsigned int len)
2513 {
2514 unsigned long hash = init_name_hash(salt);
2515 while (len--)
2516 hash = partial_name_hash((unsigned char)*name++, hash);
2517 return end_name_hash(hash);
2518 }
2519 EXPORT_SYMBOL(full_name_hash);
2520
2521 /* Return the "hash_len" (hash and length) of a null-terminated string */
hashlen_string(const void * salt,const char * name)2522 u64 hashlen_string(const void *salt, const char *name)
2523 {
2524 unsigned long hash = init_name_hash(salt);
2525 unsigned long len = 0, c;
2526
2527 c = (unsigned char)*name;
2528 while (c) {
2529 len++;
2530 hash = partial_name_hash(c, hash);
2531 c = (unsigned char)name[len];
2532 }
2533 return hashlen_create(end_name_hash(hash), len);
2534 }
2535 EXPORT_SYMBOL(hashlen_string);
2536
2537 /*
2538 * We know there's a real path component here of at least
2539 * one character.
2540 */
hash_name(struct nameidata * nd,const char * name,unsigned long * lastword)2541 static inline const char *hash_name(struct nameidata *nd, const char *name, unsigned long *lastword)
2542 {
2543 unsigned long hash = init_name_hash(nd->path.dentry);
2544 unsigned long len = 0, c, last = 0;
2545
2546 c = (unsigned char)*name;
2547 do {
2548 last = (last << 8) + c;
2549 len++;
2550 hash = partial_name_hash(c, hash);
2551 c = (unsigned char)name[len];
2552 } while (c && c != '/');
2553
2554 // This is reliable for DOT or DOTDOT, since the component
2555 // cannot contain NUL characters - top bits being zero means
2556 // we cannot have had any other pathnames.
2557 *lastword = last;
2558 nd->last.hash = end_name_hash(hash);
2559 nd->last.len = len;
2560 return name + len;
2561 }
2562
2563 #endif
2564
2565 #ifndef LAST_WORD_IS_DOT
2566 #define LAST_WORD_IS_DOT 0x2e
2567 #define LAST_WORD_IS_DOTDOT 0x2e2e
2568 #endif
2569
2570 /*
2571 * Name resolution.
2572 * This is the basic name resolution function, turning a pathname into
2573 * the final dentry. We expect 'base' to be positive and a directory.
2574 *
2575 * Returns 0 and nd will have valid dentry and mnt on success.
2576 * Returns error and drops reference to input namei data on failure.
2577 */
link_path_walk(const char * name,struct nameidata * nd)2578 static int link_path_walk(const char *name, struct nameidata *nd)
2579 {
2580 int depth = 0; // depth <= nd->depth
2581 int err;
2582
2583 nd->last_type = LAST_ROOT;
2584 nd->flags |= LOOKUP_PARENT;
2585 if (IS_ERR(name))
2586 return PTR_ERR(name);
2587 if (*name == '/') {
2588 do {
2589 name++;
2590 } while (unlikely(*name == '/'));
2591 }
2592 if (unlikely(!*name)) {
2593 nd->dir_mode = 0; // short-circuit the 'hardening' idiocy
2594 return 0;
2595 }
2596
2597 /* At this point we know we have a real path component. */
2598 for(;;) {
2599 struct mnt_idmap *idmap;
2600 const char *link;
2601 unsigned long lastword;
2602
2603 idmap = mnt_idmap(nd->path.mnt);
2604 err = may_lookup(idmap, nd);
2605 if (unlikely(err))
2606 return err;
2607
2608 nd->last.name = name;
2609 name = hash_name(nd, name, &lastword);
2610
2611 switch(lastword) {
2612 case LAST_WORD_IS_DOTDOT:
2613 nd->last_type = LAST_DOTDOT;
2614 nd->state |= ND_JUMPED;
2615 break;
2616
2617 case LAST_WORD_IS_DOT:
2618 nd->last_type = LAST_DOT;
2619 break;
2620
2621 default:
2622 nd->last_type = LAST_NORM;
2623 nd->state &= ~ND_JUMPED;
2624
2625 struct dentry *parent = nd->path.dentry;
2626 if (unlikely(parent->d_flags & DCACHE_OP_HASH)) {
2627 err = parent->d_op->d_hash(parent, &nd->last);
2628 if (err < 0)
2629 return err;
2630 }
2631 }
2632
2633 if (!*name)
2634 goto OK;
2635 /*
2636 * If it wasn't NUL, we know it was '/'. Skip that
2637 * slash, and continue until no more slashes.
2638 */
2639 do {
2640 name++;
2641 } while (unlikely(*name == '/'));
2642 if (unlikely(!*name)) {
2643 OK:
2644 /* pathname or trailing symlink, done */
2645 if (likely(!depth)) {
2646 nd->dir_vfsuid = i_uid_into_vfsuid(idmap, nd->inode);
2647 nd->dir_mode = nd->inode->i_mode;
2648 nd->flags &= ~LOOKUP_PARENT;
2649 return 0;
2650 }
2651 /* last component of nested symlink */
2652 name = nd->stack[--depth].name;
2653 link = walk_component(nd, 0);
2654 } else {
2655 /* not the last component */
2656 link = walk_component(nd, WALK_MORE);
2657 }
2658 if (unlikely(link)) {
2659 if (IS_ERR(link))
2660 return PTR_ERR(link);
2661 /* a symlink to follow */
2662 nd->stack[depth++].name = name;
2663 name = link;
2664 continue;
2665 }
2666 if (unlikely(!d_can_lookup(nd->path.dentry))) {
2667 if (nd->flags & LOOKUP_RCU) {
2668 if (!try_to_unlazy(nd))
2669 return -ECHILD;
2670 }
2671 return -ENOTDIR;
2672 }
2673 }
2674 }
2675
2676 /* must be paired with terminate_walk() */
path_init(struct nameidata * nd,unsigned flags)2677 static const char *path_init(struct nameidata *nd, unsigned flags)
2678 {
2679 int error;
2680 const char *s = nd->pathname;
2681
2682 /* LOOKUP_CACHED requires RCU, ask caller to retry */
2683 if (unlikely((flags & (LOOKUP_RCU | LOOKUP_CACHED)) == LOOKUP_CACHED))
2684 return ERR_PTR(-EAGAIN);
2685
2686 if (unlikely(!*s))
2687 flags &= ~LOOKUP_RCU;
2688 if (flags & LOOKUP_RCU)
2689 rcu_read_lock();
2690 else
2691 nd->seq = nd->next_seq = 0;
2692
2693 nd->flags = flags;
2694 nd->state |= ND_JUMPED;
2695
2696 nd->m_seq = __read_seqcount_begin(&mount_lock.seqcount);
2697 nd->r_seq = __read_seqcount_begin(&rename_lock.seqcount);
2698 smp_rmb();
2699
2700 if (unlikely(nd->state & ND_ROOT_PRESET)) {
2701 struct dentry *root = nd->root.dentry;
2702 struct inode *inode = root->d_inode;
2703 if (*s && unlikely(!d_can_lookup(root)))
2704 return ERR_PTR(-ENOTDIR);
2705 nd->path = nd->root;
2706 nd->inode = inode;
2707 if (flags & LOOKUP_RCU) {
2708 nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
2709 nd->root_seq = nd->seq;
2710 } else {
2711 path_get(&nd->path);
2712 }
2713 return s;
2714 }
2715
2716 nd->root.mnt = NULL;
2717
2718 /* Absolute pathname -- fetch the root (LOOKUP_IN_ROOT uses nd->dfd). */
2719 if (*s == '/' && likely(!(flags & LOOKUP_IN_ROOT))) {
2720 error = nd_jump_root(nd);
2721 if (unlikely(error))
2722 return ERR_PTR(error);
2723 return s;
2724 }
2725
2726 /* Relative pathname -- get the starting-point it is relative to. */
2727 if (nd->dfd == AT_FDCWD) {
2728 if (flags & LOOKUP_RCU) {
2729 struct fs_struct *fs = current->fs;
2730 unsigned seq;
2731
2732 do {
2733 seq = read_seqbegin(&fs->seq);
2734 nd->path = fs->pwd;
2735 nd->inode = nd->path.dentry->d_inode;
2736 nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
2737 } while (read_seqretry(&fs->seq, seq));
2738 } else {
2739 get_fs_pwd(current->fs, &nd->path);
2740 nd->inode = nd->path.dentry->d_inode;
2741 }
2742 } else {
2743 /* Caller must check execute permissions on the starting path component */
2744 CLASS(fd_raw, f)(nd->dfd);
2745 struct dentry *dentry;
2746
2747 if (fd_empty(f))
2748 return ERR_PTR(-EBADF);
2749
2750 if (flags & LOOKUP_LINKAT_EMPTY) {
2751 if (fd_file(f)->f_cred != current_cred() &&
2752 !ns_capable(fd_file(f)->f_cred->user_ns, CAP_DAC_READ_SEARCH))
2753 return ERR_PTR(-ENOENT);
2754 }
2755
2756 dentry = fd_file(f)->f_path.dentry;
2757
2758 if (*s && unlikely(!d_can_lookup(dentry)))
2759 return ERR_PTR(-ENOTDIR);
2760
2761 nd->path = fd_file(f)->f_path;
2762 if (flags & LOOKUP_RCU) {
2763 nd->inode = nd->path.dentry->d_inode;
2764 nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
2765 } else {
2766 path_get(&nd->path);
2767 nd->inode = nd->path.dentry->d_inode;
2768 }
2769 }
2770
2771 /* For scoped-lookups we need to set the root to the dirfd as well. */
2772 if (unlikely(flags & LOOKUP_IS_SCOPED)) {
2773 nd->root = nd->path;
2774 if (flags & LOOKUP_RCU) {
2775 nd->root_seq = nd->seq;
2776 } else {
2777 path_get(&nd->root);
2778 nd->state |= ND_ROOT_GRABBED;
2779 }
2780 }
2781 return s;
2782 }
2783
lookup_last(struct nameidata * nd)2784 static inline const char *lookup_last(struct nameidata *nd)
2785 {
2786 if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len])
2787 nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
2788
2789 return walk_component(nd, WALK_TRAILING);
2790 }
2791
handle_lookup_down(struct nameidata * nd)2792 static int handle_lookup_down(struct nameidata *nd)
2793 {
2794 if (!(nd->flags & LOOKUP_RCU))
2795 dget(nd->path.dentry);
2796 nd->next_seq = nd->seq;
2797 return PTR_ERR(step_into(nd, WALK_NOFOLLOW, nd->path.dentry));
2798 }
2799
2800 /* Returns 0 and nd will be valid on success; Returns error, otherwise. */
path_lookupat(struct nameidata * nd,unsigned flags,struct path * path)2801 static int path_lookupat(struct nameidata *nd, unsigned flags, struct path *path)
2802 {
2803 const char *s = path_init(nd, flags);
2804 int err;
2805
2806 if (unlikely(flags & LOOKUP_DOWN) && !IS_ERR(s)) {
2807 err = handle_lookup_down(nd);
2808 if (unlikely(err < 0))
2809 s = ERR_PTR(err);
2810 }
2811
2812 while (!(err = link_path_walk(s, nd)) &&
2813 (s = lookup_last(nd)) != NULL)
2814 ;
2815 if (!err && unlikely(nd->flags & LOOKUP_MOUNTPOINT)) {
2816 err = handle_lookup_down(nd);
2817 nd->state &= ~ND_JUMPED; // no d_weak_revalidate(), please...
2818 }
2819 if (!err)
2820 err = complete_walk(nd);
2821
2822 if (!err && nd->flags & LOOKUP_DIRECTORY)
2823 if (!d_can_lookup(nd->path.dentry))
2824 err = -ENOTDIR;
2825 if (!err) {
2826 *path = nd->path;
2827 nd->path.mnt = NULL;
2828 nd->path.dentry = NULL;
2829 }
2830 terminate_walk(nd);
2831 return err;
2832 }
2833
filename_lookup(int dfd,struct filename * name,unsigned flags,struct path * path,const struct path * root)2834 int filename_lookup(int dfd, struct filename *name, unsigned flags,
2835 struct path *path, const struct path *root)
2836 {
2837 int retval;
2838 struct nameidata nd;
2839 if (IS_ERR(name))
2840 return PTR_ERR(name);
2841 set_nameidata(&nd, dfd, name, root);
2842 retval = path_lookupat(&nd, flags | LOOKUP_RCU, path);
2843 if (unlikely(retval == -ECHILD))
2844 retval = path_lookupat(&nd, flags, path);
2845 if (unlikely(retval == -ESTALE))
2846 retval = path_lookupat(&nd, flags | LOOKUP_REVAL, path);
2847
2848 if (likely(!retval))
2849 audit_inode(name, path->dentry,
2850 flags & LOOKUP_MOUNTPOINT ? AUDIT_INODE_NOEVAL : 0);
2851 restore_nameidata();
2852 return retval;
2853 }
2854
2855 /* Returns 0 and nd will be valid on success; Returns error, otherwise. */
path_parentat(struct nameidata * nd,unsigned flags,struct path * parent)2856 static int path_parentat(struct nameidata *nd, unsigned flags,
2857 struct path *parent)
2858 {
2859 const char *s = path_init(nd, flags);
2860 int err = link_path_walk(s, nd);
2861 if (!err)
2862 err = complete_walk(nd);
2863 if (!err) {
2864 *parent = nd->path;
2865 nd->path.mnt = NULL;
2866 nd->path.dentry = NULL;
2867 }
2868 terminate_walk(nd);
2869 return err;
2870 }
2871
2872 /* Note: this does not consume "name" */
__filename_parentat(int dfd,struct filename * name,unsigned int flags,struct path * parent,struct qstr * last,enum last_type * type,const struct path * root)2873 static int __filename_parentat(int dfd, struct filename *name,
2874 unsigned int flags, struct path *parent,
2875 struct qstr *last, enum last_type *type,
2876 const struct path *root)
2877 {
2878 int retval;
2879 struct nameidata nd;
2880
2881 if (IS_ERR(name))
2882 return PTR_ERR(name);
2883 set_nameidata(&nd, dfd, name, root);
2884 retval = path_parentat(&nd, flags | LOOKUP_RCU, parent);
2885 if (unlikely(retval == -ECHILD))
2886 retval = path_parentat(&nd, flags, parent);
2887 if (unlikely(retval == -ESTALE))
2888 retval = path_parentat(&nd, flags | LOOKUP_REVAL, parent);
2889 if (likely(!retval)) {
2890 *last = nd.last;
2891 *type = nd.last_type;
2892 audit_inode(name, parent->dentry, AUDIT_INODE_PARENT);
2893 }
2894 restore_nameidata();
2895 return retval;
2896 }
2897
filename_parentat(int dfd,struct filename * name,unsigned int flags,struct path * parent,struct qstr * last,enum last_type * type)2898 static int filename_parentat(int dfd, struct filename *name,
2899 unsigned int flags, struct path *parent,
2900 struct qstr *last, enum last_type *type)
2901 {
2902 return __filename_parentat(dfd, name, flags, parent, last, type, NULL);
2903 }
2904
__start_dirop(struct dentry * parent,struct qstr * name,unsigned int lookup_flags,unsigned int state)2905 static struct dentry *__start_dirop(struct dentry *parent, struct qstr *name,
2906 unsigned int lookup_flags,
2907 unsigned int state)
2908 {
2909 struct dentry *dentry;
2910 struct inode *dir = d_inode(parent);
2911
2912 if (state == TASK_KILLABLE) {
2913 int ret = down_write_killable_nested(&dir->i_rwsem,
2914 I_MUTEX_PARENT);
2915 if (ret)
2916 return ERR_PTR(ret);
2917 } else {
2918 inode_lock_nested(dir, I_MUTEX_PARENT);
2919 }
2920 dentry = lookup_one_qstr_excl(name, parent, lookup_flags);
2921 if (IS_ERR(dentry))
2922 inode_unlock(dir);
2923 return dentry;
2924 }
2925
2926 /**
2927 * start_dirop - begin a create or remove dirop, performing locking and lookup
2928 * @parent: the dentry of the parent in which the operation will occur
2929 * @name: a qstr holding the name within that parent
2930 * @lookup_flags: intent and other lookup flags.
2931 *
2932 * The lookup is performed and necessary locks are taken so that, on success,
2933 * the returned dentry can be operated on safely.
2934 * The qstr must already have the hash value calculated.
2935 *
2936 * Returns: a locked dentry, or an error.
2937 *
2938 */
start_dirop(struct dentry * parent,struct qstr * name,unsigned int lookup_flags)2939 struct dentry *start_dirop(struct dentry *parent, struct qstr *name,
2940 unsigned int lookup_flags)
2941 {
2942 return __start_dirop(parent, name, lookup_flags, TASK_NORMAL);
2943 }
2944
2945 /**
2946 * end_dirop - signal completion of a dirop
2947 * @de: the dentry which was returned by start_dirop or similar.
2948 *
2949 * If the de is an error, nothing happens. Otherwise any lock taken to
2950 * protect the dentry is dropped and the dentry itself is release (dput()).
2951 */
end_dirop(struct dentry * de)2952 void end_dirop(struct dentry *de)
2953 {
2954 if (!IS_ERR(de)) {
2955 inode_unlock(de->d_parent->d_inode);
2956 dput(de);
2957 }
2958 }
2959 EXPORT_SYMBOL(end_dirop);
2960
2961 /* does lookup, returns the object with parent locked */
start_removing_path(const char * name,struct path * path)2962 struct dentry *start_removing_path(const char *name, struct path *path)
2963 {
2964 CLASS(filename_kernel, filename)(name);
2965 struct path parent_path __free(path_put) = {};
2966 struct dentry *d;
2967 struct qstr last;
2968 enum last_type type;
2969 int error;
2970
2971 error = filename_parentat(AT_FDCWD, filename, 0, &parent_path, &last,
2972 &type);
2973 if (error)
2974 return ERR_PTR(error);
2975 if (unlikely(type != LAST_NORM))
2976 return ERR_PTR(-EINVAL);
2977 /* don't fail immediately if it's r/o, at least try to report other errors */
2978 error = mnt_want_write(parent_path.mnt);
2979 d = start_dirop(parent_path.dentry, &last, 0);
2980 if (IS_ERR(d))
2981 goto drop;
2982 if (error)
2983 goto fail;
2984 path->dentry = no_free_ptr(parent_path.dentry);
2985 path->mnt = no_free_ptr(parent_path.mnt);
2986 return d;
2987
2988 fail:
2989 end_dirop(d);
2990 d = ERR_PTR(error);
2991 drop:
2992 if (!error)
2993 mnt_drop_write(parent_path.mnt);
2994 return d;
2995 }
2996
2997 /**
2998 * kern_path_parent: lookup path returning parent and target
2999 * @name: path name
3000 * @path: path to store parent in
3001 *
3002 * The path @name should end with a normal component, not "." or ".." or "/".
3003 * A lookup is performed and if successful the parent information
3004 * is store in @parent and the dentry is returned.
3005 *
3006 * The dentry maybe negative, the parent will be positive.
3007 *
3008 * Returns: dentry or error.
3009 */
kern_path_parent(const char * name,struct path * path)3010 struct dentry *kern_path_parent(const char *name, struct path *path)
3011 {
3012 struct path parent_path __free(path_put) = {};
3013 CLASS(filename_kernel, filename)(name);
3014 struct dentry *d;
3015 struct qstr last;
3016 enum last_type type;
3017 int error;
3018
3019 error = filename_parentat(AT_FDCWD, filename, 0, &parent_path, &last, &type);
3020 if (error)
3021 return ERR_PTR(error);
3022 if (unlikely(type != LAST_NORM))
3023 return ERR_PTR(-EINVAL);
3024
3025 d = lookup_noperm_unlocked(&last, parent_path.dentry);
3026 if (IS_ERR(d))
3027 return d;
3028 path->dentry = no_free_ptr(parent_path.dentry);
3029 path->mnt = no_free_ptr(parent_path.mnt);
3030 return d;
3031 }
3032
kern_path(const char * name,unsigned int flags,struct path * path)3033 int kern_path(const char *name, unsigned int flags, struct path *path)
3034 {
3035 CLASS(filename_kernel, filename)(name);
3036 return filename_lookup(AT_FDCWD, filename, flags, path, NULL);
3037 }
3038 EXPORT_SYMBOL(kern_path);
3039
3040 /**
3041 * vfs_path_parent_lookup - lookup a parent path relative to a dentry-vfsmount pair
3042 * @filename: filename structure
3043 * @flags: lookup flags
3044 * @parent: pointer to struct path to fill
3045 * @last: last component
3046 * @root: pointer to struct path of the base directory
3047 */
vfs_path_parent_lookup(struct filename * filename,unsigned int flags,struct path * parent,struct qstr * last,const struct path * root)3048 int vfs_path_parent_lookup(struct filename *filename, unsigned int flags,
3049 struct path *parent, struct qstr *last,
3050 const struct path *root)
3051 {
3052 enum last_type type;
3053 int err = __filename_parentat(AT_FDCWD, filename, flags, parent, last,
3054 &type, root);
3055 if (err)
3056 return err;
3057 if (unlikely(type != LAST_NORM)) {
3058 path_put(parent);
3059 return -EINVAL;
3060 }
3061 return 0;
3062 }
3063 EXPORT_SYMBOL(vfs_path_parent_lookup);
3064
3065 /**
3066 * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
3067 * @dentry: pointer to dentry of the base directory
3068 * @mnt: pointer to vfs mount of the base directory
3069 * @name: pointer to file name
3070 * @flags: lookup flags
3071 * @path: pointer to struct path to fill
3072 */
vfs_path_lookup(struct dentry * dentry,struct vfsmount * mnt,const char * name,unsigned int flags,struct path * path)3073 int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
3074 const char *name, unsigned int flags,
3075 struct path *path)
3076 {
3077 CLASS(filename_kernel, filename)(name);
3078 struct path root = {.mnt = mnt, .dentry = dentry};
3079
3080 /* the first argument of filename_lookup() is ignored with root */
3081 return filename_lookup(AT_FDCWD, filename, flags, path, &root);
3082 }
3083 EXPORT_SYMBOL(vfs_path_lookup);
3084
lookup_noperm_common(struct qstr * qname,struct dentry * base)3085 int lookup_noperm_common(struct qstr *qname, struct dentry *base)
3086 {
3087 const char *name = qname->name;
3088 u32 len = qname->len;
3089
3090 qname->hash = full_name_hash(base, name, len);
3091 if (!len)
3092 return -EACCES;
3093
3094 if (name_is_dot_dotdot(name, len))
3095 return -EACCES;
3096
3097 while (len--) {
3098 unsigned int c = *(const unsigned char *)name++;
3099 if (c == '/' || c == '\0')
3100 return -EACCES;
3101 }
3102 /*
3103 * See if the low-level filesystem might want
3104 * to use its own hash..
3105 */
3106 if (base->d_flags & DCACHE_OP_HASH) {
3107 int err = base->d_op->d_hash(base, qname);
3108 if (err < 0)
3109 return err;
3110 }
3111 return 0;
3112 }
3113
lookup_one_common(struct mnt_idmap * idmap,struct qstr * qname,struct dentry * base)3114 static int lookup_one_common(struct mnt_idmap *idmap,
3115 struct qstr *qname, struct dentry *base)
3116 {
3117 int err;
3118 err = lookup_noperm_common(qname, base);
3119 if (err < 0)
3120 return err;
3121 return inode_permission(idmap, base->d_inode, MAY_EXEC);
3122 }
3123
3124 /**
3125 * try_lookup_noperm - filesystem helper to lookup single pathname component
3126 * @name: qstr storing pathname component to lookup
3127 * @base: base directory to lookup from
3128 *
3129 * Look up a dentry by name in the dcache, returning NULL if it does not
3130 * currently exist or an error if there is a problem with the name.
3131 * The function does not try to create a dentry and if one
3132 * is found it doesn't try to revalidate it.
3133 *
3134 * Note that this routine is purely a helper for filesystem usage and should
3135 * not be called by generic code. It does no permission checking.
3136 *
3137 * No locks need be held - only a counted reference to @base is needed.
3138 *
3139 * Returns:
3140 * - ref-counted dentry on success, or
3141 * - %NULL if name could not be found, or
3142 * - ERR_PTR(-EACCES) if name is dot or dotdot or contains a slash or nul, or
3143 * - ERR_PTR() if fs provide ->d_hash, and this returned an error.
3144 */
try_lookup_noperm(struct qstr * name,struct dentry * base)3145 struct dentry *try_lookup_noperm(struct qstr *name, struct dentry *base)
3146 {
3147 int err;
3148
3149 err = lookup_noperm_common(name, base);
3150 if (err)
3151 return ERR_PTR(err);
3152
3153 return d_lookup(base, name);
3154 }
3155 EXPORT_SYMBOL(try_lookup_noperm);
3156
3157 /**
3158 * lookup_noperm - filesystem helper to lookup single pathname component
3159 * @name: qstr storing pathname component to lookup
3160 * @base: base directory to lookup from
3161 *
3162 * Note that this routine is purely a helper for filesystem usage and should
3163 * not be called by generic code. It does no permission checking.
3164 *
3165 * The caller must hold base->i_rwsem.
3166 */
lookup_noperm(struct qstr * name,struct dentry * base)3167 struct dentry *lookup_noperm(struct qstr *name, struct dentry *base)
3168 {
3169 struct dentry *dentry;
3170 int err;
3171
3172 WARN_ON_ONCE(!inode_is_locked(base->d_inode));
3173
3174 err = lookup_noperm_common(name, base);
3175 if (err)
3176 return ERR_PTR(err);
3177
3178 dentry = lookup_dcache(name, base, 0);
3179 return dentry ? dentry : __lookup_slow(name, base, 0);
3180 }
3181 EXPORT_SYMBOL(lookup_noperm);
3182
3183 /**
3184 * lookup_one - lookup single pathname component
3185 * @idmap: idmap of the mount the lookup is performed from
3186 * @name: qstr holding pathname component to lookup
3187 * @base: base directory to lookup from
3188 *
3189 * This can be used for in-kernel filesystem clients such as file servers.
3190 *
3191 * The caller must hold base->i_rwsem.
3192 */
lookup_one(struct mnt_idmap * idmap,struct qstr * name,struct dentry * base)3193 struct dentry *lookup_one(struct mnt_idmap *idmap, struct qstr *name,
3194 struct dentry *base)
3195 {
3196 struct dentry *dentry;
3197 int err;
3198
3199 WARN_ON_ONCE(!inode_is_locked(base->d_inode));
3200
3201 err = lookup_one_common(idmap, name, base);
3202 if (err)
3203 return ERR_PTR(err);
3204
3205 dentry = lookup_dcache(name, base, 0);
3206 return dentry ? dentry : __lookup_slow(name, base, 0);
3207 }
3208 EXPORT_SYMBOL(lookup_one);
3209
3210 /**
3211 * lookup_one_unlocked - lookup single pathname component
3212 * @idmap: idmap of the mount the lookup is performed from
3213 * @name: qstr olding pathname component to lookup
3214 * @base: base directory to lookup from
3215 *
3216 * This can be used for in-kernel filesystem clients such as file servers.
3217 *
3218 * Unlike lookup_one, it should be called without the parent
3219 * i_rwsem held, and will take the i_rwsem itself if necessary.
3220 *
3221 * Returns: - A dentry, possibly negative, or
3222 * - same errors as try_lookup_noperm() or
3223 * - ERR_PTR(-ENOENT) if parent has been removed, or
3224 * - ERR_PTR(-EACCES) if parent directory is not searchable.
3225 */
lookup_one_unlocked(struct mnt_idmap * idmap,struct qstr * name,struct dentry * base)3226 struct dentry *lookup_one_unlocked(struct mnt_idmap *idmap, struct qstr *name,
3227 struct dentry *base)
3228 {
3229 int err;
3230 struct dentry *ret;
3231
3232 err = lookup_one_common(idmap, name, base);
3233 if (err)
3234 return ERR_PTR(err);
3235
3236 ret = lookup_dcache(name, base, 0);
3237 if (!ret)
3238 ret = lookup_slow(name, base, 0);
3239 return ret;
3240 }
3241 EXPORT_SYMBOL(lookup_one_unlocked);
3242
3243 /**
3244 * lookup_one_positive_killable - lookup single pathname component
3245 * @idmap: idmap of the mount the lookup is performed from
3246 * @name: qstr olding pathname component to lookup
3247 * @base: base directory to lookup from
3248 *
3249 * This helper will yield ERR_PTR(-ENOENT) on negatives. The helper returns
3250 * known positive or ERR_PTR(). This is what most of the users want.
3251 *
3252 * Note that pinned negative with unlocked parent _can_ become positive at any
3253 * time, so callers of lookup_one_unlocked() need to be very careful; pinned
3254 * positives have >d_inode stable, so this one avoids such problems.
3255 *
3256 * This can be used for in-kernel filesystem clients such as file servers.
3257 *
3258 * It should be called without the parent i_rwsem held, and will take
3259 * the i_rwsem itself if necessary. If a fatal signal is pending or
3260 * delivered, it will return %-EINTR if the lock is needed.
3261 *
3262 * Returns: A dentry, possibly negative, or
3263 * - same errors as lookup_one_unlocked() or
3264 * - ERR_PTR(-EINTR) if a fatal signal is pending.
3265 */
lookup_one_positive_killable(struct mnt_idmap * idmap,struct qstr * name,struct dentry * base)3266 struct dentry *lookup_one_positive_killable(struct mnt_idmap *idmap,
3267 struct qstr *name,
3268 struct dentry *base)
3269 {
3270 int err;
3271 struct dentry *ret;
3272
3273 err = lookup_one_common(idmap, name, base);
3274 if (err)
3275 return ERR_PTR(err);
3276
3277 ret = lookup_dcache(name, base, 0);
3278 if (!ret)
3279 ret = lookup_slow_killable(name, base, 0);
3280 if (!IS_ERR(ret) && d_flags_negative(smp_load_acquire(&ret->d_flags))) {
3281 dput(ret);
3282 ret = ERR_PTR(-ENOENT);
3283 }
3284 return ret;
3285 }
3286 EXPORT_SYMBOL(lookup_one_positive_killable);
3287
3288 /**
3289 * lookup_one_positive_unlocked - lookup single pathname component
3290 * @idmap: idmap of the mount the lookup is performed from
3291 * @name: qstr holding pathname component to lookup
3292 * @base: base directory to lookup from
3293 *
3294 * This helper will yield ERR_PTR(-ENOENT) on negatives. The helper returns
3295 * known positive or ERR_PTR(). This is what most of the users want.
3296 *
3297 * Note that pinned negative with unlocked parent _can_ become positive at any
3298 * time, so callers of lookup_one_unlocked() need to be very careful; pinned
3299 * positives have >d_inode stable, so this one avoids such problems.
3300 *
3301 * This can be used for in-kernel filesystem clients such as file servers.
3302 *
3303 * The helper should be called without i_rwsem held.
3304 *
3305 * Returns: A positive dentry, or
3306 * - ERR_PTR(-ENOENT) if the name could not be found, or
3307 * - same errors as lookup_one_unlocked().
3308 */
lookup_one_positive_unlocked(struct mnt_idmap * idmap,struct qstr * name,struct dentry * base)3309 struct dentry *lookup_one_positive_unlocked(struct mnt_idmap *idmap,
3310 struct qstr *name,
3311 struct dentry *base)
3312 {
3313 struct dentry *ret = lookup_one_unlocked(idmap, name, base);
3314
3315 if (!IS_ERR(ret) && d_flags_negative(smp_load_acquire(&ret->d_flags))) {
3316 dput(ret);
3317 ret = ERR_PTR(-ENOENT);
3318 }
3319 return ret;
3320 }
3321 EXPORT_SYMBOL(lookup_one_positive_unlocked);
3322
3323 /**
3324 * lookup_noperm_unlocked - filesystem helper to lookup single pathname component
3325 * @name: pathname component to lookup
3326 * @base: base directory to lookup from
3327 *
3328 * Note that this routine is purely a helper for filesystem usage and should
3329 * not be called by generic code. It does no permission checking.
3330 *
3331 * Unlike lookup_noperm(), it should be called without the parent
3332 * i_rwsem held, and will take the i_rwsem itself if necessary.
3333 *
3334 * Unlike try_lookup_noperm() it *does* revalidate the dentry if it already
3335 * existed.
3336 *
3337 * Returns: A dentry, possibly negative, or
3338 * - ERR_PTR(-ENOENT) if parent has been removed, or
3339 * - same errors as try_lookup_noperm()
3340 */
lookup_noperm_unlocked(struct qstr * name,struct dentry * base)3341 struct dentry *lookup_noperm_unlocked(struct qstr *name, struct dentry *base)
3342 {
3343 struct dentry *ret;
3344 int err;
3345
3346 err = lookup_noperm_common(name, base);
3347 if (err)
3348 return ERR_PTR(err);
3349
3350 ret = lookup_dcache(name, base, 0);
3351 if (!ret)
3352 ret = lookup_slow(name, base, 0);
3353 return ret;
3354 }
3355 EXPORT_SYMBOL(lookup_noperm_unlocked);
3356
3357 /*
3358 * Like lookup_noperm_unlocked(), except that it yields ERR_PTR(-ENOENT)
3359 * on negatives. Returns known positive or ERR_PTR(); that's what
3360 * most of the users want. Note that pinned negative with unlocked parent
3361 * _can_ become positive at any time, so callers of lookup_noperm_unlocked()
3362 * need to be very careful; pinned positives have ->d_inode stable, so
3363 * this one avoids such problems.
3364 *
3365 * Returns: A positive dentry, or
3366 * - ERR_PTR(-ENOENT) if name cannot be found or parent has been removed, or
3367 * - same errors as try_lookup_noperm()
3368 */
lookup_noperm_positive_unlocked(struct qstr * name,struct dentry * base)3369 struct dentry *lookup_noperm_positive_unlocked(struct qstr *name,
3370 struct dentry *base)
3371 {
3372 struct dentry *ret;
3373
3374 ret = lookup_noperm_unlocked(name, base);
3375 if (!IS_ERR(ret) && d_flags_negative(smp_load_acquire(&ret->d_flags))) {
3376 dput(ret);
3377 ret = ERR_PTR(-ENOENT);
3378 }
3379 return ret;
3380 }
3381 EXPORT_SYMBOL(lookup_noperm_positive_unlocked);
3382
3383 /**
3384 * start_creating - prepare to create a given name with permission checking
3385 * @idmap: idmap of the mount
3386 * @parent: directory in which to prepare to create the name
3387 * @name: the name to be created
3388 *
3389 * Locks are taken and a lookup is performed prior to creating
3390 * an object in a directory. Permission checking (MAY_EXEC) is performed
3391 * against @idmap.
3392 *
3393 * If the name already exists, a positive dentry is returned, so
3394 * behaviour is similar to O_CREAT without O_EXCL, which doesn't fail
3395 * with -EEXIST.
3396 *
3397 * Returns: a negative or positive dentry, or an error.
3398 */
start_creating(struct mnt_idmap * idmap,struct dentry * parent,struct qstr * name)3399 struct dentry *start_creating(struct mnt_idmap *idmap, struct dentry *parent,
3400 struct qstr *name)
3401 {
3402 int err = lookup_one_common(idmap, name, parent);
3403
3404 if (err)
3405 return ERR_PTR(err);
3406 return start_dirop(parent, name, LOOKUP_CREATE);
3407 }
3408 EXPORT_SYMBOL(start_creating);
3409
3410 /**
3411 * start_removing - prepare to remove a given name with permission checking
3412 * @idmap: idmap of the mount
3413 * @parent: directory in which to find the name
3414 * @name: the name to be removed
3415 *
3416 * Locks are taken and a lookup in performed prior to removing
3417 * an object from a directory. Permission checking (MAY_EXEC) is performed
3418 * against @idmap.
3419 *
3420 * If the name doesn't exist, an error is returned.
3421 *
3422 * end_removing() should be called when removal is complete, or aborted.
3423 *
3424 * Returns: a positive dentry, or an error.
3425 */
start_removing(struct mnt_idmap * idmap,struct dentry * parent,struct qstr * name)3426 struct dentry *start_removing(struct mnt_idmap *idmap, struct dentry *parent,
3427 struct qstr *name)
3428 {
3429 int err = lookup_one_common(idmap, name, parent);
3430
3431 if (err)
3432 return ERR_PTR(err);
3433 return start_dirop(parent, name, 0);
3434 }
3435 EXPORT_SYMBOL(start_removing);
3436
3437 /**
3438 * start_creating_killable - prepare to create a given name with permission checking
3439 * @idmap: idmap of the mount
3440 * @parent: directory in which to prepare to create the name
3441 * @name: the name to be created
3442 *
3443 * Locks are taken and a lookup in performed prior to creating
3444 * an object in a directory. Permission checking (MAY_EXEC) is performed
3445 * against @idmap.
3446 *
3447 * If the name already exists, a positive dentry is returned.
3448 *
3449 * If a signal is received or was already pending, the function aborts
3450 * with -EINTR;
3451 *
3452 * Returns: a negative or positive dentry, or an error.
3453 */
start_creating_killable(struct mnt_idmap * idmap,struct dentry * parent,struct qstr * name)3454 struct dentry *start_creating_killable(struct mnt_idmap *idmap,
3455 struct dentry *parent,
3456 struct qstr *name)
3457 {
3458 int err = lookup_one_common(idmap, name, parent);
3459
3460 if (err)
3461 return ERR_PTR(err);
3462 return __start_dirop(parent, name, LOOKUP_CREATE, TASK_KILLABLE);
3463 }
3464 EXPORT_SYMBOL(start_creating_killable);
3465
3466 /**
3467 * start_removing_killable - prepare to remove a given name with permission checking
3468 * @idmap: idmap of the mount
3469 * @parent: directory in which to find the name
3470 * @name: the name to be removed
3471 *
3472 * Locks are taken and a lookup in performed prior to removing
3473 * an object from a directory. Permission checking (MAY_EXEC) is performed
3474 * against @idmap.
3475 *
3476 * If the name doesn't exist, an error is returned.
3477 *
3478 * end_removing() should be called when removal is complete, or aborted.
3479 *
3480 * If a signal is received or was already pending, the function aborts
3481 * with -EINTR;
3482 *
3483 * Returns: a positive dentry, or an error.
3484 */
start_removing_killable(struct mnt_idmap * idmap,struct dentry * parent,struct qstr * name)3485 struct dentry *start_removing_killable(struct mnt_idmap *idmap,
3486 struct dentry *parent,
3487 struct qstr *name)
3488 {
3489 int err = lookup_one_common(idmap, name, parent);
3490
3491 if (err)
3492 return ERR_PTR(err);
3493 return __start_dirop(parent, name, 0, TASK_KILLABLE);
3494 }
3495 EXPORT_SYMBOL(start_removing_killable);
3496
3497 /**
3498 * start_creating_noperm - prepare to create a given name without permission checking
3499 * @parent: directory in which to prepare to create the name
3500 * @name: the name to be created
3501 *
3502 * Locks are taken and a lookup in performed prior to creating
3503 * an object in a directory.
3504 *
3505 * If the name already exists, a positive dentry is returned.
3506 *
3507 * Returns: a negative or positive dentry, or an error.
3508 */
start_creating_noperm(struct dentry * parent,struct qstr * name)3509 struct dentry *start_creating_noperm(struct dentry *parent,
3510 struct qstr *name)
3511 {
3512 int err = lookup_noperm_common(name, parent);
3513
3514 if (err)
3515 return ERR_PTR(err);
3516 return start_dirop(parent, name, LOOKUP_CREATE);
3517 }
3518 EXPORT_SYMBOL(start_creating_noperm);
3519
3520 /**
3521 * start_removing_noperm - prepare to remove a given name without permission checking
3522 * @parent: directory in which to find the name
3523 * @name: the name to be removed
3524 *
3525 * Locks are taken and a lookup in performed prior to removing
3526 * an object from a directory.
3527 *
3528 * If the name doesn't exist, an error is returned.
3529 *
3530 * end_removing() should be called when removal is complete, or aborted.
3531 *
3532 * Returns: a positive dentry, or an error.
3533 */
start_removing_noperm(struct dentry * parent,struct qstr * name)3534 struct dentry *start_removing_noperm(struct dentry *parent,
3535 struct qstr *name)
3536 {
3537 int err = lookup_noperm_common(name, parent);
3538
3539 if (err)
3540 return ERR_PTR(err);
3541 return start_dirop(parent, name, 0);
3542 }
3543 EXPORT_SYMBOL(start_removing_noperm);
3544
3545 /**
3546 * start_creating_dentry - prepare to create a given dentry
3547 * @parent: directory from which dentry should be removed
3548 * @child: the dentry to be removed
3549 *
3550 * A lock is taken to protect the dentry again other dirops and
3551 * the validity of the dentry is checked: correct parent and still hashed.
3552 *
3553 * If the dentry is valid and negative a reference is taken and
3554 * returned. If not an error is returned.
3555 *
3556 * end_creating() should be called when creation is complete, or aborted.
3557 *
3558 * Returns: the valid dentry, or an error.
3559 */
start_creating_dentry(struct dentry * parent,struct dentry * child)3560 struct dentry *start_creating_dentry(struct dentry *parent,
3561 struct dentry *child)
3562 {
3563 inode_lock_nested(parent->d_inode, I_MUTEX_PARENT);
3564 if (unlikely(IS_DEADDIR(parent->d_inode) ||
3565 child->d_parent != parent ||
3566 d_unhashed(child))) {
3567 inode_unlock(parent->d_inode);
3568 return ERR_PTR(-EINVAL);
3569 }
3570 if (d_is_positive(child)) {
3571 inode_unlock(parent->d_inode);
3572 return ERR_PTR(-EEXIST);
3573 }
3574 return dget(child);
3575 }
3576 EXPORT_SYMBOL(start_creating_dentry);
3577
3578 /**
3579 * start_removing_dentry - prepare to remove a given dentry
3580 * @parent: directory from which dentry should be removed
3581 * @child: the dentry to be removed
3582 *
3583 * A lock is taken to protect the dentry again other dirops and
3584 * the validity of the dentry is checked: correct parent and still hashed.
3585 *
3586 * If the dentry is valid and positive, a reference is taken and
3587 * returned. If not an error is returned.
3588 *
3589 * end_removing() should be called when removal is complete, or aborted.
3590 *
3591 * Returns: the valid dentry, or an error.
3592 */
start_removing_dentry(struct dentry * parent,struct dentry * child)3593 struct dentry *start_removing_dentry(struct dentry *parent,
3594 struct dentry *child)
3595 {
3596 inode_lock_nested(parent->d_inode, I_MUTEX_PARENT);
3597 if (unlikely(IS_DEADDIR(parent->d_inode) ||
3598 child->d_parent != parent ||
3599 d_unhashed(child))) {
3600 inode_unlock(parent->d_inode);
3601 return ERR_PTR(-EINVAL);
3602 }
3603 if (d_is_negative(child)) {
3604 inode_unlock(parent->d_inode);
3605 return ERR_PTR(-ENOENT);
3606 }
3607 return dget(child);
3608 }
3609 EXPORT_SYMBOL(start_removing_dentry);
3610
3611 #ifdef CONFIG_UNIX98_PTYS
path_pts(struct path * path)3612 int path_pts(struct path *path)
3613 {
3614 /* Find something mounted on "pts" in the same directory as
3615 * the input path.
3616 */
3617 struct dentry *parent = dget_parent(path->dentry);
3618 struct dentry *child;
3619
3620 if (unlikely(!path_connected(path->mnt, parent))) {
3621 dput(parent);
3622 return -ENOENT;
3623 }
3624 dput(path->dentry);
3625 path->dentry = parent;
3626 child = d_hash_and_lookup(parent, &QSTR("pts"));
3627 if (IS_ERR_OR_NULL(child))
3628 return -ENOENT;
3629
3630 path->dentry = child;
3631 dput(parent);
3632 follow_down(path, 0);
3633 return 0;
3634 }
3635 #endif
3636
user_path_at(int dfd,const char __user * name,unsigned flags,struct path * path)3637 int user_path_at(int dfd, const char __user *name, unsigned flags,
3638 struct path *path)
3639 {
3640 CLASS(filename_flags, filename)(name, flags);
3641 return filename_lookup(dfd, filename, flags, path, NULL);
3642 }
3643 EXPORT_SYMBOL(user_path_at);
3644
__check_sticky(struct mnt_idmap * idmap,struct inode * dir,struct inode * inode)3645 int __check_sticky(struct mnt_idmap *idmap, struct inode *dir,
3646 struct inode *inode)
3647 {
3648 kuid_t fsuid = current_fsuid();
3649
3650 if (vfsuid_eq_kuid(i_uid_into_vfsuid(idmap, inode), fsuid))
3651 return 0;
3652 if (vfsuid_eq_kuid(i_uid_into_vfsuid(idmap, dir), fsuid))
3653 return 0;
3654 return !capable_wrt_inode_uidgid(idmap, inode, CAP_FOWNER);
3655 }
3656 EXPORT_SYMBOL(__check_sticky);
3657
3658 /*
3659 * Check whether we can remove a link victim from directory dir, check
3660 * whether the type of victim is right.
3661 * 1. We can't do it if dir is read-only (done in permission())
3662 * 2. We should have write and exec permissions on dir
3663 * 3. We can't remove anything from append-only dir
3664 * 4. We can't do anything with immutable dir (done in permission())
3665 * 5. If the sticky bit on dir is set we should either
3666 * a. be owner of dir, or
3667 * b. be owner of victim, or
3668 * c. have CAP_FOWNER capability
3669 * 6. If the victim is append-only or immutable we can't do antyhing with
3670 * links pointing to it.
3671 * 7. If the victim has an unknown uid or gid we can't change the inode.
3672 * 8. If we were asked to remove a directory and victim isn't one - ENOTDIR.
3673 * 9. If we were asked to remove a non-directory and victim isn't one - EISDIR.
3674 * 10. We can't remove a root or mountpoint.
3675 * 11. We don't allow removal of NFS sillyrenamed files; it's handled by
3676 * nfs_async_unlink().
3677 */
may_delete_dentry(struct mnt_idmap * idmap,struct inode * dir,struct dentry * victim,bool isdir)3678 int may_delete_dentry(struct mnt_idmap *idmap, struct inode *dir,
3679 struct dentry *victim, bool isdir)
3680 {
3681 struct inode *inode = d_backing_inode(victim);
3682 int error;
3683
3684 if (d_is_negative(victim))
3685 return -ENOENT;
3686 BUG_ON(!inode);
3687
3688 BUG_ON(victim->d_parent->d_inode != dir);
3689
3690 /* Inode writeback is not safe when the uid or gid are invalid. */
3691 if (!vfsuid_valid(i_uid_into_vfsuid(idmap, inode)) ||
3692 !vfsgid_valid(i_gid_into_vfsgid(idmap, inode)))
3693 return -EOVERFLOW;
3694
3695 audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
3696
3697 error = inode_permission(idmap, dir, MAY_WRITE | MAY_EXEC);
3698 if (error)
3699 return error;
3700 if (IS_APPEND(dir))
3701 return -EPERM;
3702
3703 if (check_sticky(idmap, dir, inode) || IS_APPEND(inode) ||
3704 IS_IMMUTABLE(inode) || IS_SWAPFILE(inode) ||
3705 HAS_UNMAPPED_ID(idmap, inode))
3706 return -EPERM;
3707 if (isdir) {
3708 if (!d_is_dir(victim))
3709 return -ENOTDIR;
3710 if (IS_ROOT(victim))
3711 return -EBUSY;
3712 } else if (d_is_dir(victim))
3713 return -EISDIR;
3714 if (IS_DEADDIR(dir))
3715 return -ENOENT;
3716 if (victim->d_flags & DCACHE_NFSFS_RENAMED)
3717 return -EBUSY;
3718 return 0;
3719 }
3720 EXPORT_SYMBOL(may_delete_dentry);
3721
3722 /* Check whether we can create an object with dentry child in directory
3723 * dir.
3724 * 1. We can't do it if child already exists (open has special treatment for
3725 * this case, but since we are inlined it's OK)
3726 * 2. We can't do it if dir is read-only (done in permission())
3727 * 3. We can't do it if the fs can't represent the fsuid or fsgid.
3728 * 4. We should have write and exec permissions on dir
3729 * 5. We can't do it if dir is immutable (done in permission())
3730 */
may_create_dentry(struct mnt_idmap * idmap,struct inode * dir,struct dentry * child)3731 int may_create_dentry(struct mnt_idmap *idmap,
3732 struct inode *dir, struct dentry *child)
3733 {
3734 audit_inode_child(dir, child, AUDIT_TYPE_CHILD_CREATE);
3735 if (child->d_inode)
3736 return -EEXIST;
3737 if (IS_DEADDIR(dir))
3738 return -ENOENT;
3739 if (!fsuidgid_has_mapping(dir->i_sb, idmap))
3740 return -EOVERFLOW;
3741
3742 return inode_permission(idmap, dir, MAY_WRITE | MAY_EXEC);
3743 }
3744 EXPORT_SYMBOL(may_create_dentry);
3745
3746 // p1 != p2, both are on the same filesystem, ->s_vfs_rename_mutex is held
lock_two_directories(struct dentry * p1,struct dentry * p2)3747 static struct dentry *lock_two_directories(struct dentry *p1, struct dentry *p2)
3748 {
3749 struct dentry *p = p1, *q = p2, *r;
3750
3751 while ((r = p->d_parent) != p2 && r != p)
3752 p = r;
3753 if (r == p2) {
3754 // p is a child of p2 and an ancestor of p1 or p1 itself
3755 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
3756 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT2);
3757 return p;
3758 }
3759 // p is the root of connected component that contains p1
3760 // p2 does not occur on the path from p to p1
3761 while ((r = q->d_parent) != p1 && r != p && r != q)
3762 q = r;
3763 if (r == p1) {
3764 // q is a child of p1 and an ancestor of p2 or p2 itself
3765 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
3766 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT2);
3767 return q;
3768 } else if (likely(r == p)) {
3769 // both p2 and p1 are descendents of p
3770 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
3771 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT2);
3772 return NULL;
3773 } else { // no common ancestor at the time we'd been called
3774 mutex_unlock(&p1->d_sb->s_vfs_rename_mutex);
3775 return ERR_PTR(-EXDEV);
3776 }
3777 }
3778
3779 /*
3780 * p1 and p2 should be directories on the same fs.
3781 */
lock_rename(struct dentry * p1,struct dentry * p2)3782 static struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
3783 {
3784 if (p1 == p2) {
3785 inode_lock_nested(p1->d_inode, I_MUTEX_PARENT);
3786 return NULL;
3787 }
3788
3789 mutex_lock(&p1->d_sb->s_vfs_rename_mutex);
3790 return lock_two_directories(p1, p2);
3791 }
3792
3793 /*
3794 * c1 and p2 should be on the same fs.
3795 */
lock_rename_child(struct dentry * c1,struct dentry * p2)3796 static struct dentry *lock_rename_child(struct dentry *c1, struct dentry *p2)
3797 {
3798 if (READ_ONCE(c1->d_parent) == p2) {
3799 /*
3800 * hopefully won't need to touch ->s_vfs_rename_mutex at all.
3801 */
3802 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
3803 /*
3804 * now that p2 is locked, nobody can move in or out of it,
3805 * so the test below is safe.
3806 */
3807 if (likely(c1->d_parent == p2))
3808 return NULL;
3809
3810 /*
3811 * c1 got moved out of p2 while we'd been taking locks;
3812 * unlock and fall back to slow case.
3813 */
3814 inode_unlock(p2->d_inode);
3815 }
3816
3817 mutex_lock(&c1->d_sb->s_vfs_rename_mutex);
3818 /*
3819 * nobody can move out of any directories on this fs.
3820 */
3821 if (likely(c1->d_parent != p2))
3822 return lock_two_directories(c1->d_parent, p2);
3823
3824 /*
3825 * c1 got moved into p2 while we were taking locks;
3826 * we need p2 locked and ->s_vfs_rename_mutex unlocked,
3827 * for consistency with lock_rename().
3828 */
3829 inode_lock_nested(p2->d_inode, I_MUTEX_PARENT);
3830 mutex_unlock(&c1->d_sb->s_vfs_rename_mutex);
3831 return NULL;
3832 }
3833
unlock_rename(struct dentry * p1,struct dentry * p2)3834 static void unlock_rename(struct dentry *p1, struct dentry *p2)
3835 {
3836 inode_unlock(p1->d_inode);
3837 if (p1 != p2) {
3838 inode_unlock(p2->d_inode);
3839 mutex_unlock(&p1->d_sb->s_vfs_rename_mutex);
3840 }
3841 }
3842
3843 /**
3844 * __start_renaming - lookup and lock names for rename
3845 * @rd: rename data containing parents and flags, and
3846 * for receiving found dentries
3847 * @lookup_flags: extra flags to pass to ->lookup (e.g. LOOKUP_REVAL,
3848 * LOOKUP_NO_SYMLINKS etc).
3849 * @old_last: name of object in @rd.old_parent
3850 * @new_last: name of object in @rd.new_parent
3851 *
3852 * Look up two names and ensure locks are in place for
3853 * rename.
3854 *
3855 * On success the found dentries are stored in @rd.old_dentry,
3856 * @rd.new_dentry and an extra ref is taken on @rd.old_parent.
3857 * These references and the lock are dropped by end_renaming().
3858 *
3859 * The passed in qstrs must have the hash calculated, and no permission
3860 * checking is performed.
3861 *
3862 * Returns: zero or an error.
3863 */
3864 static int
__start_renaming(struct renamedata * rd,int lookup_flags,struct qstr * old_last,struct qstr * new_last)3865 __start_renaming(struct renamedata *rd, int lookup_flags,
3866 struct qstr *old_last, struct qstr *new_last)
3867 {
3868 struct dentry *trap;
3869 struct dentry *d1, *d2;
3870 int target_flags = LOOKUP_RENAME_TARGET | LOOKUP_CREATE;
3871 int err;
3872
3873 if (rd->flags & RENAME_EXCHANGE)
3874 target_flags = 0;
3875 if (rd->flags & RENAME_NOREPLACE)
3876 target_flags |= LOOKUP_EXCL;
3877
3878 trap = lock_rename(rd->old_parent, rd->new_parent);
3879 if (IS_ERR(trap))
3880 return PTR_ERR(trap);
3881
3882 d1 = lookup_one_qstr_excl(old_last, rd->old_parent,
3883 lookup_flags);
3884 err = PTR_ERR(d1);
3885 if (IS_ERR(d1))
3886 goto out_unlock;
3887
3888 d2 = lookup_one_qstr_excl(new_last, rd->new_parent,
3889 lookup_flags | target_flags);
3890 err = PTR_ERR(d2);
3891 if (IS_ERR(d2))
3892 goto out_dput_d1;
3893
3894 if (d1 == trap) {
3895 /* source is an ancestor of target */
3896 err = -EINVAL;
3897 goto out_dput_d2;
3898 }
3899
3900 if (d2 == trap) {
3901 /* target is an ancestor of source */
3902 if (rd->flags & RENAME_EXCHANGE)
3903 err = -EINVAL;
3904 else
3905 err = -ENOTEMPTY;
3906 goto out_dput_d2;
3907 }
3908
3909 rd->old_dentry = d1;
3910 rd->new_dentry = d2;
3911 dget(rd->old_parent);
3912 return 0;
3913
3914 out_dput_d2:
3915 dput(d2);
3916 out_dput_d1:
3917 dput(d1);
3918 out_unlock:
3919 unlock_rename(rd->old_parent, rd->new_parent);
3920 return err;
3921 }
3922
3923 /**
3924 * start_renaming - lookup and lock names for rename with permission checking
3925 * @rd: rename data containing parents and flags, and
3926 * for receiving found dentries
3927 * @lookup_flags: extra flags to pass to ->lookup (e.g. LOOKUP_REVAL,
3928 * LOOKUP_NO_SYMLINKS etc).
3929 * @old_last: name of object in @rd.old_parent
3930 * @new_last: name of object in @rd.new_parent
3931 *
3932 * Look up two names and ensure locks are in place for
3933 * rename.
3934 *
3935 * On success the found dentries are stored in @rd.old_dentry,
3936 * @rd.new_dentry. Also the refcount on @rd->old_parent is increased.
3937 * These references and the lock are dropped by end_renaming().
3938 *
3939 * The passed in qstrs need not have the hash calculated, and basic
3940 * eXecute permission checking is performed against @rd.mnt_idmap.
3941 *
3942 * Returns: zero or an error.
3943 */
start_renaming(struct renamedata * rd,int lookup_flags,struct qstr * old_last,struct qstr * new_last)3944 int start_renaming(struct renamedata *rd, int lookup_flags,
3945 struct qstr *old_last, struct qstr *new_last)
3946 {
3947 int err;
3948
3949 err = lookup_one_common(rd->mnt_idmap, old_last, rd->old_parent);
3950 if (err)
3951 return err;
3952 err = lookup_one_common(rd->mnt_idmap, new_last, rd->new_parent);
3953 if (err)
3954 return err;
3955 return __start_renaming(rd, lookup_flags, old_last, new_last);
3956 }
3957 EXPORT_SYMBOL(start_renaming);
3958
3959 static int
__start_renaming_dentry(struct renamedata * rd,int lookup_flags,struct dentry * old_dentry,struct qstr * new_last)3960 __start_renaming_dentry(struct renamedata *rd, int lookup_flags,
3961 struct dentry *old_dentry, struct qstr *new_last)
3962 {
3963 struct dentry *trap;
3964 struct dentry *d2;
3965 int target_flags = LOOKUP_RENAME_TARGET | LOOKUP_CREATE;
3966 int err;
3967
3968 if (rd->flags & RENAME_EXCHANGE)
3969 target_flags = 0;
3970 if (rd->flags & RENAME_NOREPLACE)
3971 target_flags |= LOOKUP_EXCL;
3972
3973 /* Already have the dentry - need to be sure to lock the correct parent */
3974 trap = lock_rename_child(old_dentry, rd->new_parent);
3975 if (IS_ERR(trap))
3976 return PTR_ERR(trap);
3977 if (d_unhashed(old_dentry) ||
3978 (rd->old_parent && rd->old_parent != old_dentry->d_parent)) {
3979 /* dentry was removed, or moved and explicit parent requested */
3980 err = -EINVAL;
3981 goto out_unlock;
3982 }
3983
3984 d2 = lookup_one_qstr_excl(new_last, rd->new_parent,
3985 lookup_flags | target_flags);
3986 err = PTR_ERR(d2);
3987 if (IS_ERR(d2))
3988 goto out_unlock;
3989
3990 if (old_dentry == trap) {
3991 /* source is an ancestor of target */
3992 err = -EINVAL;
3993 goto out_dput_d2;
3994 }
3995
3996 if (d2 == trap) {
3997 /* target is an ancestor of source */
3998 if (rd->flags & RENAME_EXCHANGE)
3999 err = -EINVAL;
4000 else
4001 err = -ENOTEMPTY;
4002 goto out_dput_d2;
4003 }
4004
4005 rd->old_dentry = dget(old_dentry);
4006 rd->new_dentry = d2;
4007 rd->old_parent = dget(old_dentry->d_parent);
4008 return 0;
4009
4010 out_dput_d2:
4011 dput(d2);
4012 out_unlock:
4013 unlock_rename(old_dentry->d_parent, rd->new_parent);
4014 return err;
4015 }
4016
4017 /**
4018 * start_renaming_dentry - lookup and lock name for rename with permission checking
4019 * @rd: rename data containing parents and flags, and
4020 * for receiving found dentries
4021 * @lookup_flags: extra flags to pass to ->lookup (e.g. LOOKUP_REVAL,
4022 * LOOKUP_NO_SYMLINKS etc).
4023 * @old_dentry: dentry of name to move
4024 * @new_last: name of target in @rd.new_parent
4025 *
4026 * Look up target name and ensure locks are in place for
4027 * rename.
4028 *
4029 * On success the found dentry is stored in @rd.new_dentry and
4030 * @rd.old_parent is confirmed to be the parent of @old_dentry. If it
4031 * was originally %NULL, it is set. In either case a reference is taken
4032 * so that end_renaming() can have a stable reference to unlock.
4033 *
4034 * References and the lock can be dropped with end_renaming()
4035 *
4036 * The passed in qstr need not have the hash calculated, and basic
4037 * eXecute permission checking is performed against @rd.mnt_idmap.
4038 *
4039 * Returns: zero or an error.
4040 */
start_renaming_dentry(struct renamedata * rd,int lookup_flags,struct dentry * old_dentry,struct qstr * new_last)4041 int start_renaming_dentry(struct renamedata *rd, int lookup_flags,
4042 struct dentry *old_dentry, struct qstr *new_last)
4043 {
4044 int err;
4045
4046 err = lookup_one_common(rd->mnt_idmap, new_last, rd->new_parent);
4047 if (err)
4048 return err;
4049 return __start_renaming_dentry(rd, lookup_flags, old_dentry, new_last);
4050 }
4051 EXPORT_SYMBOL(start_renaming_dentry);
4052
4053 /**
4054 * start_renaming_two_dentries - Lock to dentries in given parents for rename
4055 * @rd: rename data containing parent
4056 * @old_dentry: dentry of name to move
4057 * @new_dentry: dentry to move to
4058 *
4059 * Ensure locks are in place for rename and check parentage is still correct.
4060 *
4061 * On success the two dentries are stored in @rd.old_dentry and
4062 * @rd.new_dentry and @rd.old_parent and @rd.new_parent are confirmed to
4063 * be the parents of the dentries.
4064 *
4065 * References and the lock can be dropped with end_renaming()
4066 *
4067 * Returns: zero or an error.
4068 */
4069 int
start_renaming_two_dentries(struct renamedata * rd,struct dentry * old_dentry,struct dentry * new_dentry)4070 start_renaming_two_dentries(struct renamedata *rd,
4071 struct dentry *old_dentry, struct dentry *new_dentry)
4072 {
4073 struct dentry *trap;
4074 int err;
4075
4076 /* Already have the dentry - need to be sure to lock the correct parent */
4077 trap = lock_rename_child(old_dentry, rd->new_parent);
4078 if (IS_ERR(trap))
4079 return PTR_ERR(trap);
4080 err = -EINVAL;
4081 if (d_unhashed(old_dentry) ||
4082 (rd->old_parent && rd->old_parent != old_dentry->d_parent))
4083 /* old_dentry was removed, or moved and explicit parent requested */
4084 goto out_unlock;
4085 if (d_unhashed(new_dentry) ||
4086 rd->new_parent != new_dentry->d_parent)
4087 /* new_dentry was removed or moved */
4088 goto out_unlock;
4089
4090 if (old_dentry == trap)
4091 /* source is an ancestor of target */
4092 goto out_unlock;
4093
4094 if (new_dentry == trap) {
4095 /* target is an ancestor of source */
4096 if (rd->flags & RENAME_EXCHANGE)
4097 err = -EINVAL;
4098 else
4099 err = -ENOTEMPTY;
4100 goto out_unlock;
4101 }
4102
4103 err = -EEXIST;
4104 if (d_is_positive(new_dentry) && (rd->flags & RENAME_NOREPLACE))
4105 goto out_unlock;
4106
4107 rd->old_dentry = dget(old_dentry);
4108 rd->new_dentry = dget(new_dentry);
4109 rd->old_parent = dget(old_dentry->d_parent);
4110 return 0;
4111
4112 out_unlock:
4113 unlock_rename(old_dentry->d_parent, rd->new_parent);
4114 return err;
4115 }
4116 EXPORT_SYMBOL(start_renaming_two_dentries);
4117
end_renaming(struct renamedata * rd)4118 void end_renaming(struct renamedata *rd)
4119 {
4120 unlock_rename(rd->old_parent, rd->new_parent);
4121 dput(rd->old_dentry);
4122 dput(rd->new_dentry);
4123 dput(rd->old_parent);
4124 }
4125 EXPORT_SYMBOL(end_renaming);
4126
4127 /**
4128 * vfs_prepare_mode - prepare the mode to be used for a new inode
4129 * @idmap: idmap of the mount the inode was found from
4130 * @dir: parent directory of the new inode
4131 * @mode: mode of the new inode
4132 * @mask_perms: allowed permission by the vfs
4133 * @type: type of file to be created
4134 *
4135 * This helper consolidates and enforces vfs restrictions on the @mode of a new
4136 * object to be created.
4137 *
4138 * Umask stripping depends on whether the filesystem supports POSIX ACLs (see
4139 * the kernel documentation for mode_strip_umask()). Moving umask stripping
4140 * after setgid stripping allows the same ordering for both non-POSIX ACL and
4141 * POSIX ACL supporting filesystems.
4142 *
4143 * Returns: mode to be passed to the filesystem
4144 */
vfs_prepare_mode(struct mnt_idmap * idmap,const struct inode * dir,umode_t mode,umode_t mask_perms,umode_t type)4145 static inline umode_t vfs_prepare_mode(struct mnt_idmap *idmap,
4146 const struct inode *dir, umode_t mode,
4147 umode_t mask_perms, umode_t type)
4148 {
4149 mode = mode_strip_sgid(idmap, dir, mode);
4150 mode = mode_strip_umask(dir, mode);
4151
4152 /*
4153 * Apply the vfs mandated allowed permission mask and set the type of
4154 * file to be created before we call into the filesystem.
4155 */
4156 mode &= (mask_perms & ~S_IFMT);
4157 mode |= (type & S_IFMT);
4158
4159 return mode;
4160 }
4161
4162 /**
4163 * vfs_create - create new file
4164 * @idmap: idmap of the mount the inode was found from
4165 * @dentry: dentry of the child file
4166 * @mode: mode of the child file
4167 * @di: returns parent inode, if the inode is delegated.
4168 *
4169 * Create a new file.
4170 *
4171 * If the inode has been found through an idmapped mount the idmap of
4172 * the vfsmount must be passed through @idmap. This function will then take
4173 * care to map the inode according to @idmap before checking permissions.
4174 * On non-idmapped mounts or if permission checking is to be performed on the
4175 * raw inode simply pass @nop_mnt_idmap.
4176 */
vfs_create(struct mnt_idmap * idmap,struct dentry * dentry,umode_t mode,struct delegated_inode * di)4177 int vfs_create(struct mnt_idmap *idmap, struct dentry *dentry, umode_t mode,
4178 struct delegated_inode *di)
4179 {
4180 struct inode *dir = d_inode(dentry->d_parent);
4181 int error;
4182
4183 error = may_create_dentry(idmap, dir, dentry);
4184 if (error)
4185 return error;
4186
4187 if (!dir->i_op->create)
4188 return -EACCES; /* shouldn't it be ENOSYS? */
4189
4190 mode = vfs_prepare_mode(idmap, dir, mode, S_IALLUGO, S_IFREG);
4191 error = security_inode_create(dir, dentry, mode);
4192 if (error)
4193 return error;
4194 error = try_break_deleg(dir, LEASE_BREAK_DIR_CREATE, di);
4195 if (error)
4196 return error;
4197 error = dir->i_op->create(idmap, dir, dentry, mode);
4198 if (!error)
4199 fsnotify_create(dir, dentry);
4200 return error;
4201 }
4202 EXPORT_SYMBOL(vfs_create);
4203
vfs_mkobj(struct dentry * dentry,umode_t mode,int (* f)(struct dentry *,umode_t,void *),void * arg)4204 int vfs_mkobj(struct dentry *dentry, umode_t mode,
4205 int (*f)(struct dentry *, umode_t, void *),
4206 void *arg)
4207 {
4208 struct inode *dir = dentry->d_parent->d_inode;
4209 int error = may_create_dentry(&nop_mnt_idmap, dir, dentry);
4210 if (error)
4211 return error;
4212
4213 mode &= S_IALLUGO;
4214 mode |= S_IFREG;
4215 error = security_inode_create(dir, dentry, mode);
4216 if (error)
4217 return error;
4218 error = f(dentry, mode, arg);
4219 if (!error)
4220 fsnotify_create(dir, dentry);
4221 return error;
4222 }
4223 EXPORT_SYMBOL(vfs_mkobj);
4224
may_open_dev(const struct path * path)4225 bool may_open_dev(const struct path *path)
4226 {
4227 return !(path->mnt->mnt_flags & MNT_NODEV) &&
4228 !(path->mnt->mnt_sb->s_iflags & SB_I_NODEV);
4229 }
4230
may_open(struct mnt_idmap * idmap,const struct path * path,int acc_mode,int flag)4231 static int may_open(struct mnt_idmap *idmap, const struct path *path,
4232 int acc_mode, int flag)
4233 {
4234 struct dentry *dentry = path->dentry;
4235 struct inode *inode = dentry->d_inode;
4236 int error;
4237
4238 if (!inode)
4239 return -ENOENT;
4240
4241 switch (inode->i_mode & S_IFMT) {
4242 case S_IFLNK:
4243 return -ELOOP;
4244 case S_IFDIR:
4245 if (acc_mode & MAY_WRITE)
4246 return -EISDIR;
4247 if (acc_mode & MAY_EXEC)
4248 return -EACCES;
4249 break;
4250 case S_IFBLK:
4251 case S_IFCHR:
4252 if (!may_open_dev(path))
4253 return -EACCES;
4254 fallthrough;
4255 case S_IFIFO:
4256 case S_IFSOCK:
4257 if (acc_mode & MAY_EXEC)
4258 return -EACCES;
4259 flag &= ~O_TRUNC;
4260 break;
4261 case S_IFREG:
4262 if ((acc_mode & MAY_EXEC) && path_noexec(path))
4263 return -EACCES;
4264 break;
4265 default:
4266 VFS_BUG_ON_INODE(!IS_ANON_FILE(inode), inode);
4267 }
4268
4269 error = inode_permission(idmap, inode, MAY_OPEN | acc_mode);
4270 if (error)
4271 return error;
4272
4273 /*
4274 * An append-only file must be opened in append mode for writing.
4275 */
4276 if (IS_APPEND(inode)) {
4277 if ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
4278 return -EPERM;
4279 if (flag & O_TRUNC)
4280 return -EPERM;
4281 }
4282
4283 /* O_NOATIME can only be set by the owner or superuser */
4284 if (flag & O_NOATIME && !inode_owner_or_capable(idmap, inode))
4285 return -EPERM;
4286
4287 return 0;
4288 }
4289
handle_truncate(struct mnt_idmap * idmap,struct file * filp)4290 static int handle_truncate(struct mnt_idmap *idmap, struct file *filp)
4291 {
4292 const struct path *path = &filp->f_path;
4293 struct inode *inode = path->dentry->d_inode;
4294 int error = get_write_access(inode);
4295 if (error)
4296 return error;
4297
4298 error = security_file_truncate(filp);
4299 if (!error) {
4300 error = do_truncate(idmap, path->dentry, 0,
4301 ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
4302 filp);
4303 }
4304 put_write_access(inode);
4305 return error;
4306 }
4307
open_to_namei_flags(int flag)4308 static inline int open_to_namei_flags(int flag)
4309 {
4310 if ((flag & O_ACCMODE) == 3)
4311 flag--;
4312 return flag;
4313 }
4314
may_o_create(struct mnt_idmap * idmap,const struct path * dir,struct dentry * dentry,umode_t mode)4315 static int may_o_create(struct mnt_idmap *idmap,
4316 const struct path *dir, struct dentry *dentry,
4317 umode_t mode)
4318 {
4319 int error = security_path_mknod(dir, dentry, mode, 0);
4320 if (error)
4321 return error;
4322
4323 if (!fsuidgid_has_mapping(dir->dentry->d_sb, idmap))
4324 return -EOVERFLOW;
4325
4326 error = inode_permission(idmap, dir->dentry->d_inode,
4327 MAY_WRITE | MAY_EXEC);
4328 if (error)
4329 return error;
4330
4331 return security_inode_create(dir->dentry->d_inode, dentry, mode);
4332 }
4333
4334 /**
4335 * atomic_open() - atomically look up, create and open a file
4336 * @path: parent directory path
4337 * @dentry: child to ->atomic_open()
4338 * @file: file to attach child to
4339 * @open_flag: open flags
4340 * @mode: create mode
4341 * @create_error: return value from may_o_create()
4342 *
4343 * Attempt to look up, create and open @dentry, which must be negative, in a
4344 * single call into the filesystem.
4345 *
4346 * If a non-error dentry is returned then: when FMODE_OPENED is set,
4347 * the file will have been attached to @file by the filesystem calling
4348 * finish_open(). If FMODE_OPENED isn't set, the filesystem instead called
4349 * finish_no_open() and the caller will need to perform the open themselves.
4350 *
4351 * FMODE_CREATED is set when the call to ->atomic_open() actually created
4352 * the file.
4353 *
4354 * Returns: the opened or looked-up dentry, or ERR_PTR() on failure. The
4355 * reference to @dentry is consumed in either case.
4356 */
atomic_open(const struct path * path,struct dentry * dentry,struct file * file,int open_flag,umode_t mode,int create_error)4357 static struct dentry *atomic_open(const struct path *path, struct dentry *dentry,
4358 struct file *file,
4359 int open_flag, umode_t mode, int create_error)
4360 {
4361 struct dentry *const DENTRY_NOT_SET = (void *) -1UL;
4362 struct inode *dir_inode = path->dentry->d_inode;
4363 int error;
4364
4365 file->__f_path.dentry = DENTRY_NOT_SET;
4366 file->__f_path.mnt = path->mnt;
4367 error = dir_inode->i_op->atomic_open(dir_inode, dentry, file,
4368 open_to_namei_flags(open_flag), mode);
4369 d_lookup_done(dentry);
4370
4371 if (!error) {
4372 if (file->f_mode & FMODE_OPENED) {
4373 /* finish_open() called */
4374 struct dentry *opened = file->f_path.dentry;
4375
4376 if (unlikely(opened != dentry)) {
4377 dput(dentry);
4378 dentry = dget(opened);
4379 }
4380 } else if (likely(file->f_path.dentry != DENTRY_NOT_SET)) {
4381 /* finish_no_open() called */
4382 struct dentry *replaced = file->f_path.dentry;
4383
4384 if (replaced) {
4385 dput(dentry);
4386 dentry = replaced;
4387 }
4388 if (unlikely(d_is_negative(dentry)))
4389 error = -ENOENT;
4390 } else {
4391 const char *fsname = dentry->d_sb->s_type->name;
4392
4393 WARN(1, "%s: ->atomic_open() left file->f_path.dentry unset!\n",
4394 fsname);
4395 error = -EIO;
4396 }
4397 }
4398
4399 if (error) {
4400 if (unlikely(create_error) && error == -ENOENT) {
4401 /*
4402 * Should have done a create, but errored before.
4403 * Some filesystems return -ENOENT directly instead of
4404 * calling finish_no_open() with a negative dentry;
4405 * either way it should only mean the child doesn't exist,
4406 * so a refused create is safe to record here.
4407 */
4408 audit_inode_child(dir_inode, dentry, AUDIT_TYPE_CHILD_CREATE);
4409 error = create_error;
4410 }
4411 dput(dentry);
4412 dentry = ERR_PTR(error);
4413 }
4414 return dentry;
4415 }
4416
4417 /*
4418 * Look up and maybe create and open the last component.
4419 *
4420 * Takes the parent inode lock itself, exclusive if O_CREAT was requested and
4421 * shared otherwise, and drops it again before returning. The caller must not
4422 * hold it.
4423 *
4424 * On success returns the dentry of the last component. If FMODE_OPENED is set
4425 * on file->f_mode the file was also opened and attached to @file; otherwise
4426 * only lookup and creation were performed and the caller has to open it. In
4427 * the latter case the dentry may be negative if O_CREAT hadn't been specified.
4428 *
4429 * Returns ERR_PTR() on failure.
4430 */
lookup_open(struct nameidata * nd,struct file * file,const struct open_flags * op)4431 static struct dentry *lookup_open(struct nameidata *nd, struct file *file,
4432 const struct open_flags *op)
4433 {
4434 struct delegated_inode delegated_inode = { };
4435 struct mnt_idmap *idmap;
4436 struct dentry *dir = nd->path.dentry;
4437 struct inode *dir_inode = dir->d_inode;
4438 int open_flag;
4439 struct dentry *dentry;
4440 int error, create_error;
4441 umode_t mode;
4442 bool got_write;
4443
4444 retry:
4445 open_flag = op->open_flag;
4446 got_write = false;
4447 mode = op->mode;
4448 create_error = 0;
4449
4450 if (open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) {
4451 got_write = !mnt_want_write(nd->path.mnt);
4452 /*
4453 * do _not_ fail yet - we might not need that or fail with
4454 * a different error; we'll be dropping this one anyway.
4455 */
4456 }
4457 if (open_flag & O_CREAT)
4458 inode_lock(dir_inode);
4459 else
4460 inode_lock_shared(dir_inode);
4461
4462 if (unlikely(IS_DEADDIR(dir_inode))) {
4463 dentry = ERR_PTR(-ENOENT);
4464 goto out;
4465 }
4466
4467 file->f_mode &= ~FMODE_CREATED;
4468 dentry = d_lookup(dir, &nd->last);
4469 for (;;) {
4470 if (!dentry) {
4471 dentry = d_alloc_parallel(dir, &nd->last);
4472 if (IS_ERR(dentry))
4473 goto out;
4474 }
4475 if (d_in_lookup(dentry))
4476 break;
4477
4478 error = d_revalidate(dir_inode, &nd->last, dentry, nd->flags);
4479 if (likely(error > 0))
4480 break;
4481 if (error)
4482 goto out_dput;
4483 d_invalidate(dentry);
4484 dput(dentry);
4485 dentry = NULL;
4486 }
4487 if (dentry->d_inode) {
4488 /* Cached positive dentry: will open in do_open(). */
4489 goto out;
4490 }
4491
4492 if (open_flag & O_CREAT)
4493 audit_inode(nd->name, dir, AUDIT_INODE_PARENT);
4494
4495 /*
4496 * Checking write permission is tricky, bacuse we don't know if we are
4497 * going to actually need it: O_CREAT opens should work as long as the
4498 * file exists. But checking existence breaks atomicity. The trick is
4499 * to check access and if not granted clear O_CREAT from the flags.
4500 *
4501 * Another problem is returing the "right" error value (e.g. for an
4502 * O_EXCL open we want to return EEXIST not EROFS).
4503 */
4504 if (unlikely(!got_write))
4505 open_flag &= ~O_TRUNC;
4506 idmap = mnt_idmap(nd->path.mnt);
4507 if (open_flag & O_CREAT) {
4508 if (open_flag & O_EXCL)
4509 open_flag &= ~O_TRUNC;
4510 mode = vfs_prepare_mode(idmap, dir_inode, mode, mode, mode);
4511 if (likely(got_write))
4512 create_error = may_o_create(idmap, &nd->path,
4513 dentry, mode);
4514 else
4515 create_error = -EROFS;
4516 }
4517 if (create_error)
4518 open_flag &= ~O_CREAT;
4519 if (dir_inode->i_op->atomic_open) {
4520 if (nd->flags & LOOKUP_DIRECTORY)
4521 open_flag |= O_DIRECTORY;
4522 dentry = atomic_open(&nd->path, dentry, file, open_flag, mode,
4523 create_error);
4524 goto out;
4525 }
4526
4527 if (d_in_lookup(dentry)) {
4528 struct dentry *res = dir_inode->i_op->lookup(dir_inode, dentry,
4529 nd->flags);
4530 d_lookup_done(dentry);
4531 if (unlikely(res)) {
4532 if (IS_ERR(res)) {
4533 error = PTR_ERR(res);
4534 goto out_dput;
4535 }
4536 dput(dentry);
4537 dentry = res;
4538 }
4539 }
4540 if (dentry->d_inode || !(op->open_flag & O_CREAT)) {
4541 /*
4542 * No need to create a file. If lookup returned a positive
4543 * dentry, the file will be opened in do_open().
4544 */
4545 goto out;
4546 }
4547
4548 /* Negative dentry with O_CREAT flag set */
4549 audit_inode_child(dir_inode, dentry, AUDIT_TYPE_CHILD_CREATE);
4550
4551 if (unlikely(create_error)) {
4552 /* should have done a create, but we already errored */
4553 error = create_error;
4554 goto out_dput;
4555 }
4556
4557 error = try_break_deleg(dir_inode, LEASE_BREAK_DIR_CREATE, &delegated_inode);
4558 if (error)
4559 goto out_dput;
4560
4561 file->f_mode |= FMODE_CREATED;
4562 if (!dir_inode->i_op->create) {
4563 error = -EACCES;
4564 goto out_dput;
4565 }
4566
4567 error = dir_inode->i_op->create(idmap, dir_inode, dentry, mode);
4568 if (error)
4569 goto out_dput;
4570 out:
4571 if (!IS_ERR(dentry)) {
4572 if (file->f_mode & FMODE_CREATED)
4573 fsnotify_create(dir_inode, dentry);
4574 if (file->f_mode & FMODE_OPENED)
4575 fsnotify_open(file);
4576 }
4577 if ((open_flag & O_CREAT) || create_error)
4578 inode_unlock(dir_inode);
4579 else
4580 inode_unlock_shared(dir_inode);
4581
4582 if (got_write)
4583 mnt_drop_write(nd->path.mnt);
4584
4585 if (is_delegated(&delegated_inode)) {
4586 /* Must have come through out_dput: dentry is an ERR_PTR() */
4587 error = break_deleg_wait(&delegated_inode);
4588
4589 if (!error)
4590 goto retry;
4591 dentry = ERR_PTR(error);
4592 }
4593
4594 return dentry;
4595
4596 out_dput:
4597 dput(dentry);
4598 dentry = ERR_PTR(error);
4599 goto out;
4600 }
4601
4602 /**
4603 * vfs_lookup_open - open and possibly create a regular file
4604 * @parent: directory to contain file
4605 * @last: final component of file name
4606 * @open_flag: O_flags
4607 * @mode: initial permissions for file
4608 *
4609 * Open a file after lookup and/or create. This provides similar
4610 * functionality to open_last_lookups() for non-VFS users, particularly
4611 * nfsd.
4612 * It uses ->atomic_open or ->lookup / ->create / ->open as appropriate.
4613 *
4614 * If the fs object found is not a regular file then an error is returned.
4615 * In some cases, related errors are repurposed so that the caller can
4616 * determine the type of file found from the error.
4617 * -EISDIR : a directory was found
4618 * -ELOOP : a symlink was found
4619 * -ENODEV : a block or character device special file was found
4620 * -EFTYPE : any other non-regular file was found, such as FIFO or SOCK.
4621 * or ->atomic_open responded to __O_REGULAR.
4622 *
4623 * Returns: the opened struct file, or an error.
4624 */
vfs_lookup_open(struct path * parent,struct qstr * last,int open_flag,umode_t mode)4625 struct file *vfs_lookup_open(struct path *parent, struct qstr *last,
4626 int open_flag, umode_t mode)
4627 {
4628 struct file *file __free(fput) = NULL;
4629 struct nameidata nd = {};
4630 struct open_flags op = {};
4631 struct dentry *dentry;
4632 int error = 0;
4633
4634 WARN_ONCE(mode & ~S_IALLUGO, "mode must only have permission bits");
4635 WARN_ONCE(open_flag & ~(O_ACCMODE|O_CREAT|O_EXCL|O_TRUNC|__O_REGULAR),
4636 "open_flag has unsupported flags");
4637
4638 mode |= S_IFREG;
4639 open_flag |= __O_REGULAR;
4640
4641 error = lookup_noperm_common(last, parent->dentry);
4642 if (error)
4643 return ERR_PTR(error);
4644
4645 file = alloc_empty_file(open_flag, current_cred());
4646 if (IS_ERR(file))
4647 return file;
4648
4649 nd.path = *parent;
4650 nd.last = *last;
4651 nd.flags = LOOKUP_OPEN;
4652 if (open_flag & O_CREAT) {
4653 nd.flags |= LOOKUP_CREATE;
4654 if (open_flag & O_EXCL)
4655 nd.flags |= LOOKUP_EXCL;
4656 }
4657 op.open_flag = open_flag;
4658 op.mode = mode;
4659 dentry = lookup_open(&nd, file, &op);
4660
4661 if (IS_ERR(dentry))
4662 return ERR_CAST(dentry);
4663
4664 if (d_really_is_negative(dentry)) {
4665 error = -ENOENT;
4666 } else if (!(file->f_mode & FMODE_CREATED) && (open_flag & O_EXCL)) {
4667 error = -EEXIST;
4668 } else if ((dentry->d_inode->i_mode & S_IFMT) != S_IFREG) {
4669 switch (dentry->d_inode->i_mode & S_IFMT) {
4670 case S_IFDIR:
4671 error = -EISDIR;
4672 break;
4673 case S_IFLNK:
4674 error = -ELOOP;
4675 break;
4676 case S_IFBLK:
4677 case S_IFCHR:
4678 error = -ENODEV;
4679 break;
4680 case S_IFIFO:
4681 case S_IFSOCK:
4682 default:
4683 error = -EFTYPE;
4684 break;
4685 }
4686 } else if (!(file->f_mode & FMODE_OPENED)) {
4687 nd.path.dentry = dentry;
4688 error = vfs_open(&nd.path, file);
4689 }
4690 dput(dentry);
4691
4692 if (error)
4693 return ERR_PTR(error);
4694 return no_free_ptr(file);
4695 }
4696 EXPORT_SYMBOL_FOR_MODULES(vfs_lookup_open, "nfsd");
4697
trailing_slashes(struct nameidata * nd)4698 static inline bool trailing_slashes(struct nameidata *nd)
4699 {
4700 return (bool)nd->last.name[nd->last.len];
4701 }
4702
lookup_fast_for_open(struct nameidata * nd,int open_flag)4703 static struct dentry *lookup_fast_for_open(struct nameidata *nd, int open_flag)
4704 {
4705 struct dentry *dentry;
4706
4707 if (open_flag & O_CREAT) {
4708 if (trailing_slashes(nd))
4709 return ERR_PTR(-EISDIR);
4710
4711 /* Don't bother on an O_EXCL create */
4712 if (open_flag & O_EXCL)
4713 return NULL;
4714 }
4715
4716 if (trailing_slashes(nd))
4717 nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
4718
4719 dentry = lookup_fast(nd);
4720 if (IS_ERR_OR_NULL(dentry))
4721 return dentry;
4722
4723 if (open_flag & O_CREAT) {
4724 /* Discard negative dentries. Need inode_lock to do the create */
4725 if (!dentry->d_inode) {
4726 if (!(nd->flags & LOOKUP_RCU))
4727 dput(dentry);
4728 dentry = NULL;
4729 }
4730 }
4731 return dentry;
4732 }
4733
open_last_lookups(struct nameidata * nd,struct file * file,const struct open_flags * op)4734 static const char *open_last_lookups(struct nameidata *nd,
4735 struct file *file, const struct open_flags *op)
4736 {
4737 int open_flag = op->open_flag;
4738 struct dentry *dentry;
4739 const char *res;
4740
4741 nd->flags |= op->intent;
4742
4743 if (nd->last_type != LAST_NORM) {
4744 if (nd->depth)
4745 put_link(nd);
4746 return handle_dots(nd, nd->last_type);
4747 }
4748
4749 /* We _can_ be in RCU mode here */
4750 dentry = lookup_fast_for_open(nd, open_flag);
4751 if (IS_ERR(dentry))
4752 return ERR_CAST(dentry);
4753
4754 if (likely(dentry))
4755 goto finish_lookup;
4756
4757 if (!(open_flag & O_CREAT)) {
4758 if (WARN_ON_ONCE(nd->flags & LOOKUP_RCU))
4759 return ERR_PTR(-ECHILD);
4760 } else {
4761 if (nd->flags & LOOKUP_RCU) {
4762 if (!try_to_unlazy(nd))
4763 return ERR_PTR(-ECHILD);
4764 }
4765 }
4766
4767 dentry = lookup_open(nd, file, op);
4768 if (IS_ERR(dentry))
4769 return ERR_CAST(dentry);
4770
4771 if (file->f_mode & (FMODE_OPENED | FMODE_CREATED)) {
4772 dput(nd->path.dentry);
4773 nd->path.dentry = dentry;
4774 return NULL;
4775 }
4776
4777 finish_lookup:
4778 if (nd->depth)
4779 put_link(nd);
4780 res = step_into(nd, WALK_TRAILING, dentry);
4781 if (unlikely(res))
4782 nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
4783 return res;
4784 }
4785
4786 /*
4787 * Handle the last step of open()
4788 */
do_open(struct nameidata * nd,struct file * file,const struct open_flags * op)4789 static int do_open(struct nameidata *nd,
4790 struct file *file, const struct open_flags *op)
4791 {
4792 struct mnt_idmap *idmap;
4793 int open_flag = op->open_flag;
4794 bool do_truncate;
4795 int acc_mode;
4796 int error;
4797
4798 if (!(file->f_mode & (FMODE_OPENED | FMODE_CREATED))) {
4799 error = complete_walk(nd);
4800 if (error)
4801 return error;
4802 }
4803 if (!(file->f_mode & FMODE_CREATED))
4804 audit_inode(nd->name, nd->path.dentry, 0);
4805 idmap = mnt_idmap(nd->path.mnt);
4806 if (open_flag & O_CREAT) {
4807 if ((open_flag & O_EXCL) && !(file->f_mode & FMODE_CREATED))
4808 return -EEXIST;
4809 if (d_is_dir(nd->path.dentry))
4810 return -EISDIR;
4811 error = may_create_in_sticky(idmap, nd,
4812 d_backing_inode(nd->path.dentry));
4813 if (unlikely(error))
4814 return error;
4815 }
4816
4817 if ((open_flag & __O_REGULAR) && !d_is_reg(nd->path.dentry))
4818 return -EFTYPE;
4819
4820 if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry))
4821 return -ENOTDIR;
4822
4823 do_truncate = false;
4824 acc_mode = op->acc_mode;
4825 if (file->f_mode & FMODE_CREATED) {
4826 /* Don't check for write permission, don't truncate */
4827 open_flag &= ~O_TRUNC;
4828 acc_mode = 0;
4829 } else if (d_is_reg(nd->path.dentry) && open_flag & O_TRUNC) {
4830 error = mnt_want_write(nd->path.mnt);
4831 if (error)
4832 return error;
4833 do_truncate = true;
4834 }
4835 error = may_open(idmap, &nd->path, acc_mode, open_flag);
4836 if (!error && !(file->f_mode & FMODE_OPENED))
4837 error = vfs_open(&nd->path, file);
4838 if (!error)
4839 error = security_file_post_open(file, op->acc_mode);
4840 if (!error && do_truncate)
4841 error = handle_truncate(idmap, file);
4842 if (unlikely(error > 0)) {
4843 WARN_ON(1);
4844 error = -EINVAL;
4845 }
4846 if (do_truncate)
4847 mnt_drop_write(nd->path.mnt);
4848 return error;
4849 }
4850
4851 /**
4852 * vfs_tmpfile - create tmpfile
4853 * @idmap: idmap of the mount the inode was found from
4854 * @parentpath: pointer to the path of the base directory
4855 * @file: file descriptor of the new tmpfile
4856 * @mode: mode of the new tmpfile
4857 *
4858 * Create a temporary file.
4859 *
4860 * If the inode has been found through an idmapped mount the idmap of
4861 * the vfsmount must be passed through @idmap. This function will then take
4862 * care to map the inode according to @idmap before checking permissions.
4863 * On non-idmapped mounts or if permission checking is to be performed on the
4864 * raw inode simply pass @nop_mnt_idmap.
4865 */
vfs_tmpfile(struct mnt_idmap * idmap,const struct path * parentpath,struct file * file,umode_t mode)4866 int vfs_tmpfile(struct mnt_idmap *idmap,
4867 const struct path *parentpath,
4868 struct file *file, umode_t mode)
4869 {
4870 struct dentry *child;
4871 struct inode *dir = d_inode(parentpath->dentry);
4872 struct inode *inode;
4873 int error;
4874 int open_flag = file->f_flags;
4875
4876 /* A tmpfile is I_LINKABLE, so guard its owner like may_o_create(). */
4877 if (!fsuidgid_has_mapping(dir->i_sb, idmap))
4878 return -EOVERFLOW;
4879
4880 /* we want directory to be writable */
4881 error = inode_permission(idmap, dir, MAY_WRITE | MAY_EXEC);
4882 if (error)
4883 return error;
4884 if (!dir->i_op->tmpfile)
4885 return -EOPNOTSUPP;
4886 child = d_alloc(parentpath->dentry, &slash_name);
4887 if (unlikely(!child))
4888 return -ENOMEM;
4889 file->__f_path.mnt = parentpath->mnt;
4890 file->__f_path.dentry = child;
4891 mode = vfs_prepare_mode(idmap, dir, mode, mode, mode);
4892 error = dir->i_op->tmpfile(idmap, dir, file, mode);
4893 dput(child);
4894 if (file->f_mode & FMODE_OPENED)
4895 fsnotify_open(file);
4896 if (error)
4897 return error;
4898 /* Don't check for other permissions, the inode was just created */
4899 error = may_open(idmap, &file->f_path, 0, file->f_flags);
4900 if (error)
4901 return error;
4902 inode = file_inode(file);
4903 if (!(open_flag & O_EXCL)) {
4904 spin_lock(&inode->i_lock);
4905 inode_state_set(inode, I_LINKABLE);
4906 spin_unlock(&inode->i_lock);
4907 }
4908 security_inode_post_create_tmpfile(idmap, inode);
4909 return 0;
4910 }
4911
4912 /**
4913 * kernel_tmpfile_open - open a tmpfile for kernel internal use
4914 * @idmap: idmap of the mount the inode was found from
4915 * @parentpath: path of the base directory
4916 * @mode: mode of the new tmpfile
4917 * @open_flag: flags
4918 * @cred: credentials for open
4919 *
4920 * Create and open a temporary file. The file is not accounted in nr_files,
4921 * hence this is only for kernel internal use, and must not be installed into
4922 * file tables or such.
4923 */
kernel_tmpfile_open(struct mnt_idmap * idmap,const struct path * parentpath,umode_t mode,int open_flag,const struct cred * cred)4924 struct file *kernel_tmpfile_open(struct mnt_idmap *idmap,
4925 const struct path *parentpath,
4926 umode_t mode, int open_flag,
4927 const struct cred *cred)
4928 {
4929 struct file *file;
4930 int error;
4931
4932 file = alloc_empty_file_noaccount(open_flag, cred);
4933 if (IS_ERR(file))
4934 return file;
4935
4936 error = vfs_tmpfile(idmap, parentpath, file, mode);
4937 if (error) {
4938 fput(file);
4939 file = ERR_PTR(error);
4940 }
4941 return file;
4942 }
4943 EXPORT_SYMBOL(kernel_tmpfile_open);
4944
do_tmpfile(struct nameidata * nd,unsigned flags,const struct open_flags * op,struct file * file)4945 static int do_tmpfile(struct nameidata *nd, unsigned flags,
4946 const struct open_flags *op,
4947 struct file *file)
4948 {
4949 struct path path;
4950 int error = path_lookupat(nd, flags | LOOKUP_DIRECTORY, &path);
4951
4952 if (unlikely(error))
4953 return error;
4954 error = mnt_want_write(path.mnt);
4955 if (unlikely(error))
4956 goto out;
4957 error = vfs_tmpfile(mnt_idmap(path.mnt), &path, file, op->mode);
4958 if (error)
4959 goto out2;
4960 audit_inode(nd->name, file->f_path.dentry, 0);
4961 out2:
4962 mnt_drop_write(path.mnt);
4963 out:
4964 path_put(&path);
4965 return error;
4966 }
4967
do_o_path(struct nameidata * nd,unsigned flags,struct file * file)4968 static int do_o_path(struct nameidata *nd, unsigned flags, struct file *file)
4969 {
4970 struct path path;
4971 int error = path_lookupat(nd, flags, &path);
4972 if (!error) {
4973 audit_inode(nd->name, path.dentry, 0);
4974 error = vfs_open(&path, file);
4975 path_put(&path);
4976 }
4977 return error;
4978 }
4979
path_openat(struct nameidata * nd,const struct open_flags * op,unsigned flags)4980 static struct file *path_openat(struct nameidata *nd,
4981 const struct open_flags *op, unsigned flags)
4982 {
4983 struct file *file;
4984 int error;
4985
4986 file = alloc_empty_file(op->open_flag, current_cred());
4987 if (IS_ERR(file))
4988 return file;
4989
4990 if (unlikely(file->f_flags & __O_TMPFILE)) {
4991 error = do_tmpfile(nd, flags, op, file);
4992 } else if (unlikely(file->f_flags & O_PATH)) {
4993 error = do_o_path(nd, flags, file);
4994 } else {
4995 const char *s = path_init(nd, flags);
4996 while (!(error = link_path_walk(s, nd)) &&
4997 (s = open_last_lookups(nd, file, op)) != NULL)
4998 ;
4999 if (!error)
5000 error = do_open(nd, file, op);
5001 terminate_walk(nd);
5002 }
5003 if (likely(!error)) {
5004 if (likely(file->f_mode & FMODE_OPENED))
5005 return file;
5006 WARN_ON(1);
5007 error = -EINVAL;
5008 }
5009 fput_close(file);
5010 if (error == -EOPENSTALE) {
5011 if (flags & LOOKUP_RCU)
5012 error = -ECHILD;
5013 else
5014 error = -ESTALE;
5015 }
5016 return ERR_PTR(error);
5017 }
5018
do_file_open(int dfd,struct filename * pathname,const struct open_flags * op)5019 struct file *do_file_open(int dfd, struct filename *pathname,
5020 const struct open_flags *op)
5021 {
5022 struct nameidata nd;
5023 int flags = op->lookup_flags;
5024 struct file *filp;
5025
5026 if (IS_ERR(pathname))
5027 return ERR_CAST(pathname);
5028 set_nameidata(&nd, dfd, pathname, NULL);
5029 filp = path_openat(&nd, op, flags | LOOKUP_RCU);
5030 if (unlikely(filp == ERR_PTR(-ECHILD)))
5031 filp = path_openat(&nd, op, flags);
5032 if (unlikely(filp == ERR_PTR(-ESTALE)))
5033 filp = path_openat(&nd, op, flags | LOOKUP_REVAL);
5034 restore_nameidata();
5035 return filp;
5036 }
5037
do_file_open_root(const struct path * root,const char * name,const struct open_flags * op)5038 struct file *do_file_open_root(const struct path *root,
5039 const char *name, const struct open_flags *op)
5040 {
5041 struct nameidata nd;
5042 struct file *file;
5043 int flags = op->lookup_flags;
5044
5045 if (d_is_symlink(root->dentry) && op->intent & LOOKUP_OPEN)
5046 return ERR_PTR(-ELOOP);
5047
5048 CLASS(filename_kernel, filename)(name);
5049 if (IS_ERR(filename))
5050 return ERR_CAST(filename);
5051
5052 set_nameidata(&nd, -1, filename, root);
5053 file = path_openat(&nd, op, flags | LOOKUP_RCU);
5054 if (unlikely(file == ERR_PTR(-ECHILD)))
5055 file = path_openat(&nd, op, flags);
5056 if (unlikely(file == ERR_PTR(-ESTALE)))
5057 file = path_openat(&nd, op, flags | LOOKUP_REVAL);
5058 restore_nameidata();
5059 return file;
5060 }
5061
filename_create(int dfd,struct filename * name,struct path * path,unsigned int lookup_flags)5062 static struct dentry *filename_create(int dfd, struct filename *name,
5063 struct path *path, unsigned int lookup_flags)
5064 {
5065 struct dentry *dentry = ERR_PTR(-EEXIST);
5066 struct qstr last;
5067 bool want_dir = lookup_flags & LOOKUP_DIRECTORY;
5068 unsigned int reval_flag = lookup_flags & LOOKUP_REVAL;
5069 unsigned int create_flags = LOOKUP_CREATE | LOOKUP_EXCL;
5070 enum last_type type;
5071 int error;
5072
5073 error = filename_parentat(dfd, name, reval_flag, path, &last, &type);
5074 if (error)
5075 return ERR_PTR(error);
5076
5077 /*
5078 * Yucky last component or no last component at all?
5079 * (foo/., foo/.., /////)
5080 */
5081 if (unlikely(type != LAST_NORM))
5082 goto out;
5083
5084 /* don't fail immediately if it's r/o, at least try to report other errors */
5085 error = mnt_want_write(path->mnt);
5086 /*
5087 * Do the final lookup. Suppress 'create' if there is a trailing
5088 * '/', and a directory wasn't requested.
5089 */
5090 if (last.name[last.len] && !want_dir)
5091 create_flags &= ~LOOKUP_CREATE;
5092 dentry = start_dirop(path->dentry, &last, reval_flag | create_flags);
5093 if (IS_ERR(dentry))
5094 goto out_drop_write;
5095
5096 if (unlikely(error))
5097 goto fail;
5098
5099 return dentry;
5100 fail:
5101 end_dirop(dentry);
5102 dentry = ERR_PTR(error);
5103 out_drop_write:
5104 if (!error)
5105 mnt_drop_write(path->mnt);
5106 out:
5107 path_put(path);
5108 return dentry;
5109 }
5110
start_creating_path(int dfd,const char * pathname,struct path * path,unsigned int lookup_flags)5111 struct dentry *start_creating_path(int dfd, const char *pathname,
5112 struct path *path, unsigned int lookup_flags)
5113 {
5114 CLASS(filename_kernel, filename)(pathname);
5115 return filename_create(dfd, filename, path, lookup_flags);
5116 }
5117 EXPORT_SYMBOL(start_creating_path);
5118
5119 /**
5120 * end_creating_path - finish a code section started by start_creating_path()
5121 * @path: the path instantiated by start_creating_path()
5122 * @dentry: the dentry returned by start_creating_path()
5123 *
5124 * end_creating_path() will unlock and locks taken by start_creating_path()
5125 * and drop an references that were taken. It should only be called
5126 * if start_creating_path() returned a non-error.
5127 * If vfs_mkdir() was called and it returned an error, that error *should*
5128 * be passed to end_creating_path() together with the path.
5129 */
end_creating_path(const struct path * path,struct dentry * dentry)5130 void end_creating_path(const struct path *path, struct dentry *dentry)
5131 {
5132 end_creating(dentry);
5133 mnt_drop_write(path->mnt);
5134 path_put(path);
5135 }
5136 EXPORT_SYMBOL(end_creating_path);
5137
start_creating_user_path(int dfd,const char __user * pathname,struct path * path,unsigned int lookup_flags)5138 inline struct dentry *start_creating_user_path(
5139 int dfd, const char __user *pathname,
5140 struct path *path, unsigned int lookup_flags)
5141 {
5142 CLASS(filename, filename)(pathname);
5143 return filename_create(dfd, filename, path, lookup_flags);
5144 }
5145 EXPORT_SYMBOL(start_creating_user_path);
5146
5147 /**
5148 * dentry_create - Create and open a file
5149 * @path: path to create
5150 * @flags: O\_ flags
5151 * @mode: mode bits for new file
5152 * @cred: credentials to use
5153 *
5154 * Caller must hold the parent directory's lock, and have prepared
5155 * a negative dentry, placed in @path->dentry, for the new file.
5156 *
5157 * Caller sets @path->mnt to the vfsmount of the filesystem where
5158 * the new file is to be created. The parent directory and the
5159 * negative dentry must reside on the same filesystem instance.
5160 *
5161 * On success, returns a ``struct file *``. Otherwise an ERR_PTR
5162 * is returned.
5163 */
dentry_create(struct path * path,int flags,umode_t mode,const struct cred * cred)5164 struct file *dentry_create(struct path *path, int flags, umode_t mode,
5165 const struct cred *cred)
5166 {
5167 struct file *file __free(fput) = NULL;
5168 struct dentry *dentry = path->dentry;
5169 struct dentry *orig_dentry = dentry;
5170 struct dentry *dir = dentry->d_parent;
5171 struct inode *dir_inode = d_inode(dir);
5172 struct mnt_idmap *idmap;
5173 int error, create_error;
5174
5175 file = alloc_empty_file(flags, cred);
5176 if (IS_ERR(file))
5177 return file;
5178
5179 idmap = mnt_idmap(path->mnt);
5180
5181 if (dir_inode->i_op->atomic_open) {
5182 path->dentry = dir;
5183 mode = vfs_prepare_mode(idmap, dir_inode, mode, S_IALLUGO, S_IFREG);
5184
5185 create_error = may_o_create(idmap, path, dentry, mode);
5186 if (create_error)
5187 flags &= ~O_CREAT;
5188
5189 /* atomic_open will dput(dentry) on error */
5190 dget(orig_dentry);
5191 dentry = atomic_open(path, dentry, file, flags, mode, create_error);
5192 error = PTR_ERR_OR_ZERO(dentry);
5193
5194 if (IS_ERR(dentry))
5195 /* keep the original */
5196 dentry = orig_dentry;
5197 else
5198 /* Drop the extra reference */
5199 dput(orig_dentry);
5200
5201 if (!error) {
5202 if (file->f_mode & FMODE_CREATED)
5203 fsnotify_create(dir->d_inode, dentry);
5204 if (file->f_mode & FMODE_OPENED)
5205 fsnotify_open(file);
5206 }
5207
5208 path->dentry = dentry;
5209
5210 } else {
5211 error = vfs_create(mnt_idmap(path->mnt), path->dentry, mode, NULL);
5212 if (!error)
5213 error = vfs_open(path, file);
5214 }
5215 if (unlikely(error))
5216 return ERR_PTR(error);
5217
5218 return no_free_ptr(file);
5219 }
5220 EXPORT_SYMBOL(dentry_create);
5221
5222 /**
5223 * vfs_mknod - create device node or file
5224 * @idmap: idmap of the mount the inode was found from
5225 * @dir: inode of the parent directory
5226 * @dentry: dentry of the child device node
5227 * @mode: mode of the child device node
5228 * @dev: device number of device to create
5229 * @delegated_inode: returns parent inode, if the inode is delegated.
5230 *
5231 * Create a device node or file.
5232 *
5233 * If the inode has been found through an idmapped mount the idmap of
5234 * the vfsmount must be passed through @idmap. This function will then take
5235 * care to map the inode according to @idmap before checking permissions.
5236 * On non-idmapped mounts or if permission checking is to be performed on the
5237 * raw inode simply pass @nop_mnt_idmap.
5238 */
vfs_mknod(struct mnt_idmap * idmap,struct inode * dir,struct dentry * dentry,umode_t mode,dev_t dev,struct delegated_inode * delegated_inode)5239 int vfs_mknod(struct mnt_idmap *idmap, struct inode *dir,
5240 struct dentry *dentry, umode_t mode, dev_t dev,
5241 struct delegated_inode *delegated_inode)
5242 {
5243 bool is_whiteout = S_ISCHR(mode) && dev == WHITEOUT_DEV;
5244 int error = may_create_dentry(idmap, dir, dentry);
5245
5246 if (error)
5247 return error;
5248
5249 if ((S_ISCHR(mode) || S_ISBLK(mode)) && !is_whiteout &&
5250 !capable(CAP_MKNOD))
5251 return -EPERM;
5252
5253 if (!dir->i_op->mknod)
5254 return -EPERM;
5255
5256 mode = vfs_prepare_mode(idmap, dir, mode, mode, mode);
5257 error = devcgroup_inode_mknod(mode, dev);
5258 if (error)
5259 return error;
5260
5261 error = security_inode_mknod(dir, dentry, mode, dev);
5262 if (error)
5263 return error;
5264
5265 error = try_break_deleg(dir, LEASE_BREAK_DIR_CREATE, delegated_inode);
5266 if (error)
5267 return error;
5268
5269 error = dir->i_op->mknod(idmap, dir, dentry, mode, dev);
5270 if (!error)
5271 fsnotify_create(dir, dentry);
5272 return error;
5273 }
5274 EXPORT_SYMBOL(vfs_mknod);
5275
may_mknod(umode_t mode)5276 static int may_mknod(umode_t mode)
5277 {
5278 switch (mode & S_IFMT) {
5279 case S_IFREG:
5280 case S_IFCHR:
5281 case S_IFBLK:
5282 case S_IFIFO:
5283 case S_IFSOCK:
5284 case 0: /* zero mode translates to S_IFREG */
5285 return 0;
5286 case S_IFDIR:
5287 return -EPERM;
5288 default:
5289 return -EINVAL;
5290 }
5291 }
5292
filename_mknodat(int dfd,struct filename * name,umode_t mode,unsigned int dev)5293 int filename_mknodat(int dfd, struct filename *name, umode_t mode,
5294 unsigned int dev)
5295 {
5296 struct delegated_inode di = { };
5297 struct mnt_idmap *idmap;
5298 struct dentry *dentry;
5299 struct path path;
5300 int error;
5301 unsigned int lookup_flags = 0;
5302
5303 error = may_mknod(mode);
5304 if (error)
5305 return error;
5306 retry:
5307 dentry = filename_create(dfd, name, &path, lookup_flags);
5308 if (IS_ERR(dentry))
5309 return PTR_ERR(dentry);
5310
5311 error = security_path_mknod(&path, dentry,
5312 mode_strip_umask(path.dentry->d_inode, mode), dev);
5313 if (error)
5314 goto out2;
5315
5316 idmap = mnt_idmap(path.mnt);
5317 switch (mode & S_IFMT) {
5318 case 0: case S_IFREG:
5319 error = vfs_create(idmap, dentry, mode, &di);
5320 if (!error)
5321 security_path_post_mknod(idmap, dentry);
5322 break;
5323 case S_IFCHR: case S_IFBLK:
5324 error = vfs_mknod(idmap, path.dentry->d_inode,
5325 dentry, mode, new_decode_dev(dev), &di);
5326 break;
5327 case S_IFIFO: case S_IFSOCK:
5328 error = vfs_mknod(idmap, path.dentry->d_inode,
5329 dentry, mode, 0, &di);
5330 break;
5331 }
5332 out2:
5333 end_creating_path(&path, dentry);
5334 if (is_delegated(&di)) {
5335 error = break_deleg_wait(&di);
5336 if (!error)
5337 goto retry;
5338 }
5339 if (retry_estale(error, lookup_flags)) {
5340 lookup_flags |= LOOKUP_REVAL;
5341 goto retry;
5342 }
5343 return error;
5344 }
5345
SYSCALL_DEFINE4(mknodat,int,dfd,const char __user *,filename,umode_t,mode,unsigned int,dev)5346 SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode,
5347 unsigned int, dev)
5348 {
5349 CLASS(filename, name)(filename);
5350 return filename_mknodat(dfd, name, mode, dev);
5351 }
5352
SYSCALL_DEFINE3(mknod,const char __user *,filename,umode_t,mode,unsigned,dev)5353 SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
5354 {
5355 CLASS(filename, name)(filename);
5356 return filename_mknodat(AT_FDCWD, name, mode, dev);
5357 }
5358
5359 /**
5360 * vfs_mkdir - create directory returning correct dentry if possible
5361 * @idmap: idmap of the mount the inode was found from
5362 * @dir: inode of the parent directory
5363 * @dentry: dentry of the child directory
5364 * @mode: mode of the child directory
5365 * @delegated_inode: returns parent inode, if the inode is delegated.
5366 *
5367 * Create a directory.
5368 *
5369 * If the inode has been found through an idmapped mount the idmap of
5370 * the vfsmount must be passed through @idmap. This function will then take
5371 * care to map the inode according to @idmap before checking permissions.
5372 * On non-idmapped mounts or if permission checking is to be performed on the
5373 * raw inode simply pass @nop_mnt_idmap.
5374 *
5375 * In the event that the filesystem does not use the *@dentry but leaves it
5376 * negative or unhashes it and possibly splices a different one returning it,
5377 * the original dentry is dput() and the alternate is returned.
5378 *
5379 * In case of an error the dentry is dput() and an ERR_PTR() is returned.
5380 */
vfs_mkdir(struct mnt_idmap * idmap,struct inode * dir,struct dentry * dentry,umode_t mode,struct delegated_inode * delegated_inode)5381 struct dentry *vfs_mkdir(struct mnt_idmap *idmap, struct inode *dir,
5382 struct dentry *dentry, umode_t mode,
5383 struct delegated_inode *delegated_inode)
5384 {
5385 int error;
5386 unsigned max_links = dir->i_sb->s_max_links;
5387 struct dentry *de;
5388
5389 error = may_create_dentry(idmap, dir, dentry);
5390 if (error)
5391 goto err;
5392
5393 error = -EPERM;
5394 if (!dir->i_op->mkdir)
5395 goto err;
5396
5397 mode = vfs_prepare_mode(idmap, dir, mode, S_IRWXUGO | S_ISVTX, S_IFDIR);
5398 error = security_inode_mkdir(dir, dentry, mode);
5399 if (error)
5400 goto err;
5401
5402 error = -EMLINK;
5403 if (max_links && dir->i_nlink >= max_links)
5404 goto err;
5405
5406 error = try_break_deleg(dir, LEASE_BREAK_DIR_CREATE, delegated_inode);
5407 if (error)
5408 goto err;
5409
5410 de = dir->i_op->mkdir(idmap, dir, dentry, mode);
5411 error = PTR_ERR(de);
5412 if (IS_ERR(de))
5413 goto err;
5414 if (de) {
5415 dput(dentry);
5416 dentry = de;
5417 }
5418 fsnotify_mkdir(dir, dentry);
5419 return dentry;
5420
5421 err:
5422 end_creating(dentry);
5423 return ERR_PTR(error);
5424 }
5425 EXPORT_SYMBOL(vfs_mkdir);
5426
filename_mkdirat(int dfd,struct filename * name,umode_t mode)5427 int filename_mkdirat(int dfd, struct filename *name, umode_t mode)
5428 {
5429 struct dentry *dentry;
5430 struct path path;
5431 int error;
5432 unsigned int lookup_flags = LOOKUP_DIRECTORY;
5433 struct delegated_inode delegated_inode = { };
5434
5435 retry:
5436 dentry = filename_create(dfd, name, &path, lookup_flags);
5437 if (IS_ERR(dentry))
5438 return PTR_ERR(dentry);
5439
5440 error = security_path_mkdir(&path, dentry,
5441 mode_strip_umask(path.dentry->d_inode, mode));
5442 if (!error) {
5443 dentry = vfs_mkdir(mnt_idmap(path.mnt), path.dentry->d_inode,
5444 dentry, mode, &delegated_inode);
5445 if (IS_ERR(dentry))
5446 error = PTR_ERR(dentry);
5447 }
5448 end_creating_path(&path, dentry);
5449 if (is_delegated(&delegated_inode)) {
5450 error = break_deleg_wait(&delegated_inode);
5451 if (!error)
5452 goto retry;
5453 }
5454 if (retry_estale(error, lookup_flags)) {
5455 lookup_flags |= LOOKUP_REVAL;
5456 goto retry;
5457 }
5458 return error;
5459 }
5460
SYSCALL_DEFINE3(mkdirat,int,dfd,const char __user *,pathname,umode_t,mode)5461 SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode)
5462 {
5463 CLASS(filename, name)(pathname);
5464 return filename_mkdirat(dfd, name, mode);
5465 }
5466
SYSCALL_DEFINE2(mkdir,const char __user *,pathname,umode_t,mode)5467 SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode)
5468 {
5469 CLASS(filename, name)(pathname);
5470 return filename_mkdirat(AT_FDCWD, name, mode);
5471 }
5472
5473 /**
5474 * vfs_rmdir - remove directory
5475 * @idmap: idmap of the mount the inode was found from
5476 * @dir: inode of the parent directory
5477 * @dentry: dentry of the child directory
5478 * @delegated_inode: returns parent inode, if it's delegated.
5479 *
5480 * Remove a directory.
5481 *
5482 * If the inode has been found through an idmapped mount the idmap of
5483 * the vfsmount must be passed through @idmap. This function will then take
5484 * care to map the inode according to @idmap before checking permissions.
5485 * On non-idmapped mounts or if permission checking is to be performed on the
5486 * raw inode simply pass @nop_mnt_idmap.
5487 */
vfs_rmdir(struct mnt_idmap * idmap,struct inode * dir,struct dentry * dentry,struct delegated_inode * delegated_inode)5488 int vfs_rmdir(struct mnt_idmap *idmap, struct inode *dir,
5489 struct dentry *dentry, struct delegated_inode *delegated_inode)
5490 {
5491 int error = may_delete_dentry(idmap, dir, dentry, true);
5492
5493 if (error)
5494 return error;
5495
5496 if (!dir->i_op->rmdir)
5497 return -EPERM;
5498
5499 dget(dentry);
5500 inode_lock(dentry->d_inode);
5501
5502 error = -EBUSY;
5503 if (is_local_mountpoint(dentry) ||
5504 (dentry->d_inode->i_flags & S_KERNEL_FILE))
5505 goto out;
5506
5507 error = security_inode_rmdir(dir, dentry);
5508 if (error)
5509 goto out;
5510
5511 error = try_break_deleg(dir, LEASE_BREAK_DIR_DELETE, delegated_inode);
5512 if (error)
5513 goto out;
5514
5515 error = dir->i_op->rmdir(dir, dentry);
5516 if (error)
5517 goto out;
5518
5519 shrink_dcache_parent(dentry);
5520 dentry->d_inode->i_flags |= S_DEAD;
5521 dont_mount(dentry);
5522 detach_mounts(dentry);
5523
5524 out:
5525 inode_unlock(dentry->d_inode);
5526 dput(dentry);
5527 if (!error)
5528 d_delete_notify(dir, dentry);
5529 return error;
5530 }
5531 EXPORT_SYMBOL(vfs_rmdir);
5532
filename_rmdir(int dfd,struct filename * name)5533 int filename_rmdir(int dfd, struct filename *name)
5534 {
5535 int error;
5536 struct dentry *dentry;
5537 struct path path;
5538 struct qstr last;
5539 enum last_type type;
5540 unsigned int lookup_flags = 0;
5541 struct delegated_inode delegated_inode = { };
5542 retry:
5543 error = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
5544 if (error)
5545 return error;
5546
5547 switch (type) {
5548 case LAST_NORM:
5549 break;
5550 case LAST_DOTDOT:
5551 error = -ENOTEMPTY;
5552 goto exit2;
5553 case LAST_DOT:
5554 error = -EINVAL;
5555 goto exit2;
5556 case LAST_ROOT:
5557 error = -EBUSY;
5558 goto exit2;
5559 }
5560
5561 error = mnt_want_write(path.mnt);
5562 if (error)
5563 goto exit2;
5564
5565 dentry = start_dirop(path.dentry, &last, lookup_flags);
5566 error = PTR_ERR(dentry);
5567 if (IS_ERR(dentry))
5568 goto exit3;
5569 error = security_path_rmdir(&path, dentry);
5570 if (error)
5571 goto exit4;
5572 error = vfs_rmdir(mnt_idmap(path.mnt), path.dentry->d_inode,
5573 dentry, &delegated_inode);
5574 exit4:
5575 end_dirop(dentry);
5576 exit3:
5577 mnt_drop_write(path.mnt);
5578 exit2:
5579 path_put(&path);
5580 if (is_delegated(&delegated_inode)) {
5581 error = break_deleg_wait(&delegated_inode);
5582 if (!error)
5583 goto retry;
5584 }
5585 if (retry_estale(error, lookup_flags)) {
5586 lookup_flags |= LOOKUP_REVAL;
5587 goto retry;
5588 }
5589 return error;
5590 }
5591
SYSCALL_DEFINE1(rmdir,const char __user *,pathname)5592 SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
5593 {
5594 CLASS(filename, name)(pathname);
5595 return filename_rmdir(AT_FDCWD, name);
5596 }
5597
5598 /**
5599 * vfs_unlink - unlink a filesystem object
5600 * @idmap: idmap of the mount the inode was found from
5601 * @dir: parent directory
5602 * @dentry: victim
5603 * @delegated_inode: returns victim inode, if the inode is delegated.
5604 *
5605 * The caller must hold dir->i_rwsem exclusively.
5606 *
5607 * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and
5608 * return a reference to the inode in delegated_inode. The caller
5609 * should then break the delegation on that inode and retry. Because
5610 * breaking a delegation may take a long time, the caller should drop
5611 * dir->i_rwsem before doing so.
5612 *
5613 * Alternatively, a caller may pass NULL for delegated_inode. This may
5614 * be appropriate for callers that expect the underlying filesystem not
5615 * to be NFS exported.
5616 *
5617 * If the inode has been found through an idmapped mount the idmap of
5618 * the vfsmount must be passed through @idmap. This function will then take
5619 * care to map the inode according to @idmap before checking permissions.
5620 * On non-idmapped mounts or if permission checking is to be performed on the
5621 * raw inode simply pass @nop_mnt_idmap.
5622 */
vfs_unlink(struct mnt_idmap * idmap,struct inode * dir,struct dentry * dentry,struct delegated_inode * delegated_inode)5623 int vfs_unlink(struct mnt_idmap *idmap, struct inode *dir,
5624 struct dentry *dentry, struct delegated_inode *delegated_inode)
5625 {
5626 struct inode *target = dentry->d_inode;
5627 int error = may_delete_dentry(idmap, dir, dentry, false);
5628
5629 if (error)
5630 return error;
5631
5632 if (!dir->i_op->unlink)
5633 return -EPERM;
5634
5635 inode_lock(target);
5636 if (IS_SWAPFILE(target))
5637 error = -EPERM;
5638 else if (is_local_mountpoint(dentry))
5639 error = -EBUSY;
5640 else {
5641 error = security_inode_unlink(dir, dentry);
5642 if (!error) {
5643 error = try_break_deleg(dir, LEASE_BREAK_DIR_DELETE, delegated_inode);
5644 if (error)
5645 goto out;
5646 error = try_break_deleg(target, 0, delegated_inode);
5647 if (error)
5648 goto out;
5649 error = dir->i_op->unlink(dir, dentry);
5650 if (!error) {
5651 dont_mount(dentry);
5652 detach_mounts(dentry);
5653 }
5654 }
5655 }
5656 out:
5657 inode_unlock(target);
5658
5659 /* We don't d_delete() NFS sillyrenamed files--they still exist. */
5660 if (!error && dentry->d_flags & DCACHE_NFSFS_RENAMED) {
5661 fsnotify_unlink(dir, dentry);
5662 } else if (!error) {
5663 fsnotify_link_count(target);
5664 d_delete_notify(dir, dentry);
5665 }
5666
5667 return error;
5668 }
5669 EXPORT_SYMBOL(vfs_unlink);
5670
5671 /*
5672 * Make sure that the actual truncation of the file will occur outside its
5673 * directory's i_rwsem. Truncate can take a long time if there is a lot of
5674 * writeout happening, and we don't want to prevent access to the directory
5675 * while waiting on the I/O.
5676 */
filename_unlinkat(int dfd,struct filename * name)5677 int filename_unlinkat(int dfd, struct filename *name)
5678 {
5679 int error;
5680 struct dentry *dentry;
5681 struct path path;
5682 struct qstr last;
5683 enum last_type type;
5684 struct inode *inode;
5685 struct delegated_inode delegated_inode = { };
5686 unsigned int lookup_flags = 0;
5687 retry:
5688 error = filename_parentat(dfd, name, lookup_flags, &path, &last, &type);
5689 if (error)
5690 return error;
5691
5692 error = -EISDIR;
5693 if (type != LAST_NORM)
5694 goto exit_path_put;
5695
5696 error = mnt_want_write(path.mnt);
5697 if (error)
5698 goto exit_path_put;
5699 retry_deleg:
5700 dentry = start_dirop(path.dentry, &last, lookup_flags);
5701 error = PTR_ERR(dentry);
5702 if (IS_ERR(dentry))
5703 goto exit_drop_write;
5704
5705 /* Why not before? Because we want correct error value */
5706 if (unlikely(last.name[last.len])) {
5707 if (d_is_dir(dentry))
5708 error = -EISDIR;
5709 else
5710 error = -ENOTDIR;
5711 end_dirop(dentry);
5712 goto exit_drop_write;
5713 }
5714 inode = dentry->d_inode;
5715 ihold(inode);
5716 error = security_path_unlink(&path, dentry);
5717 if (error)
5718 goto exit_end_dirop;
5719 error = vfs_unlink(mnt_idmap(path.mnt), path.dentry->d_inode,
5720 dentry, &delegated_inode);
5721 exit_end_dirop:
5722 end_dirop(dentry);
5723 iput(inode); /* truncate the inode here */
5724 if (is_delegated(&delegated_inode)) {
5725 error = break_deleg_wait(&delegated_inode);
5726 if (!error)
5727 goto retry_deleg;
5728 }
5729 exit_drop_write:
5730 mnt_drop_write(path.mnt);
5731 exit_path_put:
5732 path_put(&path);
5733 if (retry_estale(error, lookup_flags)) {
5734 lookup_flags |= LOOKUP_REVAL;
5735 goto retry;
5736 }
5737 return error;
5738 }
5739
SYSCALL_DEFINE3(unlinkat,int,dfd,const char __user *,pathname,int,flag)5740 SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
5741 {
5742 if ((flag & ~AT_REMOVEDIR) != 0)
5743 return -EINVAL;
5744
5745 CLASS(filename, name)(pathname);
5746 if (flag & AT_REMOVEDIR)
5747 return filename_rmdir(dfd, name);
5748 return filename_unlinkat(dfd, name);
5749 }
5750
SYSCALL_DEFINE1(unlink,const char __user *,pathname)5751 SYSCALL_DEFINE1(unlink, const char __user *, pathname)
5752 {
5753 CLASS(filename, name)(pathname);
5754 return filename_unlinkat(AT_FDCWD, name);
5755 }
5756
5757 /**
5758 * vfs_symlink - create symlink
5759 * @idmap: idmap of the mount the inode was found from
5760 * @dir: inode of the parent directory
5761 * @dentry: dentry of the child symlink file
5762 * @oldname: name of the file to link to
5763 * @delegated_inode: returns victim inode, if the inode is delegated.
5764 *
5765 * Create a symlink.
5766 *
5767 * If the inode has been found through an idmapped mount the idmap of
5768 * the vfsmount must be passed through @idmap. This function will then take
5769 * care to map the inode according to @idmap before checking permissions.
5770 * On non-idmapped mounts or if permission checking is to be performed on the
5771 * raw inode simply pass @nop_mnt_idmap.
5772 */
vfs_symlink(struct mnt_idmap * idmap,struct inode * dir,struct dentry * dentry,const char * oldname,struct delegated_inode * delegated_inode)5773 int vfs_symlink(struct mnt_idmap *idmap, struct inode *dir,
5774 struct dentry *dentry, const char *oldname,
5775 struct delegated_inode *delegated_inode)
5776 {
5777 int error;
5778
5779 error = may_create_dentry(idmap, dir, dentry);
5780 if (error)
5781 return error;
5782
5783 if (!dir->i_op->symlink)
5784 return -EPERM;
5785
5786 error = security_inode_symlink(dir, dentry, oldname);
5787 if (error)
5788 return error;
5789
5790 error = try_break_deleg(dir, LEASE_BREAK_DIR_CREATE, delegated_inode);
5791 if (error)
5792 return error;
5793
5794 error = dir->i_op->symlink(idmap, dir, dentry, oldname);
5795 if (!error)
5796 fsnotify_create(dir, dentry);
5797 return error;
5798 }
5799 EXPORT_SYMBOL(vfs_symlink);
5800
filename_symlinkat(struct filename * from,int newdfd,struct filename * to)5801 int filename_symlinkat(struct filename *from, int newdfd, struct filename *to)
5802 {
5803 int error;
5804 struct dentry *dentry;
5805 struct path path;
5806 unsigned int lookup_flags = 0;
5807 struct delegated_inode delegated_inode = { };
5808
5809 if (IS_ERR(from))
5810 return PTR_ERR(from);
5811
5812 retry:
5813 dentry = filename_create(newdfd, to, &path, lookup_flags);
5814 if (IS_ERR(dentry))
5815 return PTR_ERR(dentry);
5816
5817 error = security_path_symlink(&path, dentry, from->name);
5818 if (!error)
5819 error = vfs_symlink(mnt_idmap(path.mnt), path.dentry->d_inode,
5820 dentry, from->name, &delegated_inode);
5821 end_creating_path(&path, dentry);
5822 if (is_delegated(&delegated_inode)) {
5823 error = break_deleg_wait(&delegated_inode);
5824 if (!error)
5825 goto retry;
5826 }
5827 if (retry_estale(error, lookup_flags)) {
5828 lookup_flags |= LOOKUP_REVAL;
5829 goto retry;
5830 }
5831 return error;
5832 }
5833
SYSCALL_DEFINE3(symlinkat,const char __user *,oldname,int,newdfd,const char __user *,newname)5834 SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
5835 int, newdfd, const char __user *, newname)
5836 {
5837 CLASS(filename, old)(oldname);
5838 CLASS(filename, new)(newname);
5839 return filename_symlinkat(old, newdfd, new);
5840 }
5841
SYSCALL_DEFINE2(symlink,const char __user *,oldname,const char __user *,newname)5842 SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
5843 {
5844 CLASS(filename, old)(oldname);
5845 CLASS(filename, new)(newname);
5846 return filename_symlinkat(old, AT_FDCWD, new);
5847 }
5848
5849 /**
5850 * vfs_link - create a new link
5851 * @old_dentry: object to be linked
5852 * @idmap: idmap of the mount
5853 * @dir: new parent
5854 * @new_dentry: where to create the new link
5855 * @delegated_inode: returns inode needing a delegation break
5856 *
5857 * The caller must hold dir->i_rwsem exclusively.
5858 *
5859 * If vfs_link discovers a delegation on the to-be-linked file in need
5860 * of breaking, it will return -EWOULDBLOCK and return a reference to the
5861 * inode in delegated_inode. The caller should then break the delegation
5862 * and retry. Because breaking a delegation may take a long time, the
5863 * caller should drop the i_rwsem before doing so.
5864 *
5865 * Alternatively, a caller may pass NULL for delegated_inode. This may
5866 * be appropriate for callers that expect the underlying filesystem not
5867 * to be NFS exported.
5868 *
5869 * If the inode has been found through an idmapped mount the idmap of
5870 * the vfsmount must be passed through @idmap. This function will then take
5871 * care to map the inode according to @idmap before checking permissions.
5872 * On non-idmapped mounts or if permission checking is to be performed on the
5873 * raw inode simply pass @nop_mnt_idmap.
5874 */
vfs_link(struct dentry * old_dentry,struct mnt_idmap * idmap,struct inode * dir,struct dentry * new_dentry,struct delegated_inode * delegated_inode)5875 int vfs_link(struct dentry *old_dentry, struct mnt_idmap *idmap,
5876 struct inode *dir, struct dentry *new_dentry,
5877 struct delegated_inode *delegated_inode)
5878 {
5879 struct inode *inode = old_dentry->d_inode;
5880 unsigned max_links = dir->i_sb->s_max_links;
5881 int error;
5882
5883 if (!inode)
5884 return -ENOENT;
5885
5886 error = may_create_dentry(idmap, dir, new_dentry);
5887 if (error)
5888 return error;
5889
5890 if (dir->i_sb != inode->i_sb)
5891 return -EXDEV;
5892
5893 /*
5894 * A link to an append-only or immutable file cannot be created.
5895 */
5896 if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
5897 return -EPERM;
5898 /*
5899 * Updating the link count will likely cause i_uid and i_gid to
5900 * be written back improperly if their true value is unknown to
5901 * the vfs.
5902 */
5903 if (HAS_UNMAPPED_ID(idmap, inode))
5904 return -EPERM;
5905 if (!dir->i_op->link)
5906 return -EPERM;
5907 if (S_ISDIR(inode->i_mode))
5908 return -EPERM;
5909
5910 error = security_inode_link(old_dentry, dir, new_dentry);
5911 if (error)
5912 return error;
5913
5914 inode_lock(inode);
5915 /* Make sure we don't allow creating hardlink to an unlinked file */
5916 if (inode->i_nlink == 0 && !(inode_state_read_once(inode) & I_LINKABLE))
5917 error = -ENOENT;
5918 else if (max_links && inode->i_nlink >= max_links)
5919 error = -EMLINK;
5920 else {
5921 error = try_break_deleg(dir, LEASE_BREAK_DIR_CREATE, delegated_inode);
5922 if (!error)
5923 error = try_break_deleg(inode, 0, delegated_inode);
5924 if (!error)
5925 error = dir->i_op->link(old_dentry, dir, new_dentry);
5926 }
5927
5928 if (!error && (inode_state_read_once(inode) & I_LINKABLE)) {
5929 spin_lock(&inode->i_lock);
5930 inode_state_clear(inode, I_LINKABLE);
5931 spin_unlock(&inode->i_lock);
5932 }
5933 inode_unlock(inode);
5934 if (!error)
5935 fsnotify_link(dir, inode, new_dentry);
5936 return error;
5937 }
5938 EXPORT_SYMBOL(vfs_link);
5939
5940 /*
5941 * Hardlinks are often used in delicate situations. We avoid
5942 * security-related surprises by not following symlinks on the
5943 * newname. --KAB
5944 *
5945 * We don't follow them on the oldname either to be compatible
5946 * with linux 2.0, and to avoid hard-linking to directories
5947 * and other special files. --ADM
5948 */
filename_linkat(int olddfd,struct filename * old,int newdfd,struct filename * new,int flags)5949 int filename_linkat(int olddfd, struct filename *old,
5950 int newdfd, struct filename *new, int flags)
5951 {
5952 struct mnt_idmap *idmap;
5953 struct dentry *new_dentry;
5954 struct path old_path, new_path;
5955 struct delegated_inode delegated_inode = { };
5956 int how = 0;
5957 int error;
5958
5959 if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0)
5960 return -EINVAL;
5961 /*
5962 * To use null names we require CAP_DAC_READ_SEARCH or
5963 * that the open-time creds of the dfd matches current.
5964 * This ensures that not everyone will be able to create
5965 * a hardlink using the passed file descriptor.
5966 */
5967 if (flags & AT_EMPTY_PATH)
5968 how |= LOOKUP_LINKAT_EMPTY;
5969
5970 if (flags & AT_SYMLINK_FOLLOW)
5971 how |= LOOKUP_FOLLOW;
5972 retry:
5973 error = filename_lookup(olddfd, old, how, &old_path, NULL);
5974 if (error)
5975 return error;
5976
5977 new_dentry = filename_create(newdfd, new, &new_path,
5978 (how & LOOKUP_REVAL));
5979 error = PTR_ERR(new_dentry);
5980 if (IS_ERR(new_dentry))
5981 goto out_putpath;
5982
5983 error = -EXDEV;
5984 if (old_path.mnt != new_path.mnt)
5985 goto out_dput;
5986 idmap = mnt_idmap(new_path.mnt);
5987 error = may_linkat(idmap, &old_path);
5988 if (unlikely(error))
5989 goto out_dput;
5990 error = security_path_link(old_path.dentry, &new_path, new_dentry);
5991 if (error)
5992 goto out_dput;
5993 error = vfs_link(old_path.dentry, idmap, new_path.dentry->d_inode,
5994 new_dentry, &delegated_inode);
5995 out_dput:
5996 end_creating_path(&new_path, new_dentry);
5997 if (is_delegated(&delegated_inode)) {
5998 error = break_deleg_wait(&delegated_inode);
5999 if (!error) {
6000 path_put(&old_path);
6001 goto retry;
6002 }
6003 }
6004 if (retry_estale(error, how)) {
6005 path_put(&old_path);
6006 how |= LOOKUP_REVAL;
6007 goto retry;
6008 }
6009 out_putpath:
6010 path_put(&old_path);
6011 return error;
6012 }
6013
SYSCALL_DEFINE5(linkat,int,olddfd,const char __user *,oldname,int,newdfd,const char __user *,newname,int,flags)6014 SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
6015 int, newdfd, const char __user *, newname, int, flags)
6016 {
6017 CLASS(filename_uflags, old)(oldname, flags);
6018 CLASS(filename, new)(newname);
6019 return filename_linkat(olddfd, old, newdfd, new, flags);
6020 }
6021
SYSCALL_DEFINE2(link,const char __user *,oldname,const char __user *,newname)6022 SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
6023 {
6024 CLASS(filename, old)(oldname);
6025 CLASS(filename, new)(newname);
6026 return filename_linkat(AT_FDCWD, old, AT_FDCWD, new, 0);
6027 }
6028
6029 /**
6030 * vfs_rename - rename a filesystem object
6031 * @rd: pointer to &struct renamedata info
6032 *
6033 * The caller must hold multiple mutexes--see lock_rename()).
6034 *
6035 * If vfs_rename discovers a delegation in need of breaking at either
6036 * the source or destination, it will return -EWOULDBLOCK and return a
6037 * reference to the inode in delegated_inode. The caller should then
6038 * break the delegation and retry. Because breaking a delegation may
6039 * take a long time, the caller should drop all locks before doing
6040 * so.
6041 *
6042 * Alternatively, a caller may pass NULL for delegated_inode. This may
6043 * be appropriate for callers that expect the underlying filesystem not
6044 * to be NFS exported.
6045 *
6046 * The worst of all namespace operations - renaming directory. "Perverted"
6047 * doesn't even start to describe it. Somebody in UCB had a heck of a trip...
6048 * Problems:
6049 *
6050 * a) we can get into loop creation.
6051 * b) race potential - two innocent renames can create a loop together.
6052 * That's where 4.4BSD screws up. Current fix: serialization on
6053 * sb->s_vfs_rename_mutex. We might be more accurate, but that's another
6054 * story.
6055 * c) we may have to lock up to _four_ objects - parents and victim (if it exists),
6056 * and source (if it's a non-directory or a subdirectory that moves to
6057 * different parent).
6058 * And that - after we got ->i_rwsem on parents (until then we don't know
6059 * whether the target exists). Solution: try to be smart with locking
6060 * order for inodes. We rely on the fact that tree topology may change
6061 * only under ->s_vfs_rename_mutex _and_ that parent of the object we
6062 * move will be locked. Thus we can rank directories by the tree
6063 * (ancestors first) and rank all non-directories after them.
6064 * That works since everybody except rename does "lock parent, lookup,
6065 * lock child" and rename is under ->s_vfs_rename_mutex.
6066 * HOWEVER, it relies on the assumption that any object with ->lookup()
6067 * has no more than 1 dentry. If "hybrid" objects will ever appear,
6068 * we'd better make sure that there's no link(2) for them.
6069 * d) conversion from fhandle to dentry may come in the wrong moment - when
6070 * we are removing the target. Solution: we will have to grab ->i_rwsem
6071 * in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
6072 * ->i_rwsem on parents, which works but leads to some truly excessive
6073 * locking].
6074 */
vfs_rename(struct renamedata * rd)6075 int vfs_rename(struct renamedata *rd)
6076 {
6077 int error;
6078 struct inode *old_dir = d_inode(rd->old_parent);
6079 struct inode *new_dir = d_inode(rd->new_parent);
6080 struct dentry *old_dentry = rd->old_dentry;
6081 struct dentry *new_dentry = rd->new_dentry;
6082 struct delegated_inode *delegated_inode = rd->delegated_inode;
6083 unsigned int flags = rd->flags;
6084 bool is_dir = d_is_dir(old_dentry);
6085 struct inode *source = old_dentry->d_inode;
6086 struct inode *target = new_dentry->d_inode;
6087 bool new_is_dir = false;
6088 unsigned max_links = new_dir->i_sb->s_max_links;
6089 struct name_snapshot old_name;
6090 bool lock_old_subdir, lock_new_subdir;
6091
6092 if (source == target)
6093 return 0;
6094
6095 error = may_delete_dentry(rd->mnt_idmap, old_dir, old_dentry, is_dir);
6096 if (error)
6097 return error;
6098
6099 if (!target) {
6100 error = may_create_dentry(rd->mnt_idmap, new_dir, new_dentry);
6101 } else {
6102 new_is_dir = d_is_dir(new_dentry);
6103
6104 if (!(flags & RENAME_EXCHANGE))
6105 error = may_delete_dentry(rd->mnt_idmap, new_dir,
6106 new_dentry, is_dir);
6107 else
6108 error = may_delete_dentry(rd->mnt_idmap, new_dir,
6109 new_dentry, new_is_dir);
6110 }
6111 if (error)
6112 return error;
6113
6114 if (!old_dir->i_op->rename)
6115 return -EPERM;
6116
6117 /*
6118 * If we are going to change the parent - check write permissions,
6119 * we'll need to flip '..'.
6120 */
6121 if (new_dir != old_dir) {
6122 if (is_dir) {
6123 error = inode_permission(rd->mnt_idmap, source,
6124 MAY_WRITE);
6125 if (error)
6126 return error;
6127 }
6128 if ((flags & RENAME_EXCHANGE) && new_is_dir) {
6129 error = inode_permission(rd->mnt_idmap, target,
6130 MAY_WRITE);
6131 if (error)
6132 return error;
6133 }
6134 }
6135
6136 error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
6137 flags);
6138 if (error)
6139 return error;
6140
6141 take_dentry_name_snapshot(&old_name, old_dentry);
6142 dget(new_dentry);
6143 /*
6144 * Lock children.
6145 * The source subdirectory needs to be locked on cross-directory
6146 * rename or cross-directory exchange since its parent changes.
6147 * The target subdirectory needs to be locked on cross-directory
6148 * exchange due to parent change and on any rename due to becoming
6149 * a victim.
6150 * Non-directories need locking in all cases (for NFS reasons);
6151 * they get locked after any subdirectories (in inode address order).
6152 *
6153 * NOTE: WE ONLY LOCK UNRELATED DIRECTORIES IN CROSS-DIRECTORY CASE.
6154 * NEVER, EVER DO THAT WITHOUT ->s_vfs_rename_mutex.
6155 */
6156 lock_old_subdir = new_dir != old_dir;
6157 lock_new_subdir = new_dir != old_dir || !(flags & RENAME_EXCHANGE);
6158 if (is_dir) {
6159 if (lock_old_subdir)
6160 inode_lock_nested(source, I_MUTEX_CHILD);
6161 if (target && (!new_is_dir || lock_new_subdir))
6162 inode_lock(target);
6163 } else if (new_is_dir) {
6164 if (lock_new_subdir)
6165 inode_lock_nested(target, I_MUTEX_CHILD);
6166 inode_lock(source);
6167 } else {
6168 lock_two_nondirectories(source, target);
6169 }
6170
6171 error = -EPERM;
6172 if (IS_SWAPFILE(source) || (target && IS_SWAPFILE(target)))
6173 goto out;
6174
6175 error = -EBUSY;
6176 if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
6177 goto out;
6178
6179 if (max_links && new_dir != old_dir) {
6180 error = -EMLINK;
6181 if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
6182 goto out;
6183 if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
6184 old_dir->i_nlink >= max_links)
6185 goto out;
6186 }
6187 error = try_break_deleg(old_dir,
6188 old_dir == new_dir ? LEASE_BREAK_DIR_RENAME :
6189 LEASE_BREAK_DIR_DELETE,
6190 delegated_inode);
6191 if (error)
6192 goto out;
6193 if (new_dir != old_dir) {
6194 error = try_break_deleg(new_dir, LEASE_BREAK_DIR_CREATE, delegated_inode);
6195 if (error)
6196 goto out;
6197 }
6198 if (!is_dir) {
6199 error = try_break_deleg(source, 0, delegated_inode);
6200 if (error)
6201 goto out;
6202 }
6203 if (target && !new_is_dir) {
6204 error = try_break_deleg(target, 0, delegated_inode);
6205 if (error)
6206 goto out;
6207 }
6208 error = old_dir->i_op->rename(rd->mnt_idmap, old_dir, old_dentry,
6209 new_dir, new_dentry, flags);
6210 if (error)
6211 goto out;
6212
6213 if (!(flags & RENAME_EXCHANGE) && target) {
6214 if (is_dir) {
6215 shrink_dcache_parent(new_dentry);
6216 target->i_flags |= S_DEAD;
6217 }
6218 dont_mount(new_dentry);
6219 detach_mounts(new_dentry);
6220 }
6221 if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
6222 if (!(flags & RENAME_EXCHANGE))
6223 d_move(old_dentry, new_dentry);
6224 else
6225 d_exchange(old_dentry, new_dentry);
6226 }
6227 out:
6228 if (!is_dir || lock_old_subdir)
6229 inode_unlock(source);
6230 if (target && (!new_is_dir || lock_new_subdir))
6231 inode_unlock(target);
6232 dput(new_dentry);
6233 if (!error) {
6234 fsnotify_move(old_dir, new_dir, &old_name.name, is_dir,
6235 !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
6236 if (flags & RENAME_EXCHANGE) {
6237 fsnotify_move(new_dir, old_dir, &old_dentry->d_name,
6238 new_is_dir, NULL, new_dentry);
6239 }
6240 }
6241 release_dentry_name_snapshot(&old_name);
6242
6243 return error;
6244 }
6245 EXPORT_SYMBOL(vfs_rename);
6246
filename_renameat2(int olddfd,struct filename * from,int newdfd,struct filename * to,unsigned int flags)6247 int filename_renameat2(int olddfd, struct filename *from,
6248 int newdfd, struct filename *to, unsigned int flags)
6249 {
6250 struct renamedata rd;
6251 struct path old_path, new_path;
6252 struct qstr old_last, new_last;
6253 enum last_type old_type, new_type;
6254 struct delegated_inode delegated_inode = { };
6255 unsigned int lookup_flags = 0;
6256 bool should_retry = false;
6257 int error;
6258
6259 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
6260 return -EINVAL;
6261
6262 if ((flags & (RENAME_NOREPLACE | RENAME_WHITEOUT)) &&
6263 (flags & RENAME_EXCHANGE))
6264 return -EINVAL;
6265
6266 retry:
6267 error = filename_parentat(olddfd, from, lookup_flags, &old_path,
6268 &old_last, &old_type);
6269 if (error)
6270 return error;
6271
6272 error = filename_parentat(newdfd, to, lookup_flags, &new_path, &new_last,
6273 &new_type);
6274 if (error)
6275 goto exit1;
6276
6277 error = -EXDEV;
6278 if (old_path.mnt != new_path.mnt)
6279 goto exit2;
6280
6281 error = -EBUSY;
6282 if (old_type != LAST_NORM)
6283 goto exit2;
6284
6285 if (flags & RENAME_NOREPLACE)
6286 error = -EEXIST;
6287 if (new_type != LAST_NORM)
6288 goto exit2;
6289
6290 error = mnt_want_write(old_path.mnt);
6291 if (error)
6292 goto exit2;
6293
6294 retry_deleg:
6295 rd.old_parent = old_path.dentry;
6296 rd.mnt_idmap = mnt_idmap(old_path.mnt);
6297 rd.new_parent = new_path.dentry;
6298 rd.delegated_inode = &delegated_inode;
6299 rd.flags = flags;
6300
6301 error = __start_renaming(&rd, lookup_flags, &old_last, &new_last);
6302 if (error)
6303 goto exit_lock_rename;
6304
6305 if (flags & RENAME_EXCHANGE) {
6306 if (!d_is_dir(rd.new_dentry)) {
6307 error = -ENOTDIR;
6308 if (new_last.name[new_last.len])
6309 goto exit_unlock;
6310 }
6311 }
6312 /* unless the source is a directory trailing slashes give -ENOTDIR */
6313 if (!d_is_dir(rd.old_dentry)) {
6314 error = -ENOTDIR;
6315 if (old_last.name[old_last.len])
6316 goto exit_unlock;
6317 if (!(flags & RENAME_EXCHANGE) && new_last.name[new_last.len])
6318 goto exit_unlock;
6319 }
6320
6321 error = security_path_rename(&old_path, rd.old_dentry,
6322 &new_path, rd.new_dentry, flags);
6323 if (error)
6324 goto exit_unlock;
6325
6326 error = vfs_rename(&rd);
6327 exit_unlock:
6328 end_renaming(&rd);
6329 exit_lock_rename:
6330 if (is_delegated(&delegated_inode)) {
6331 error = break_deleg_wait(&delegated_inode);
6332 if (!error)
6333 goto retry_deleg;
6334 }
6335 mnt_drop_write(old_path.mnt);
6336 exit2:
6337 if (retry_estale(error, lookup_flags))
6338 should_retry = true;
6339 path_put(&new_path);
6340 exit1:
6341 path_put(&old_path);
6342 if (should_retry) {
6343 should_retry = false;
6344 lookup_flags |= LOOKUP_REVAL;
6345 goto retry;
6346 }
6347 return error;
6348 }
6349
SYSCALL_DEFINE5(renameat2,int,olddfd,const char __user *,oldname,int,newdfd,const char __user *,newname,unsigned int,flags)6350 SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname,
6351 int, newdfd, const char __user *, newname, unsigned int, flags)
6352 {
6353 CLASS(filename, old)(oldname);
6354 CLASS(filename, new)(newname);
6355 return filename_renameat2(olddfd, old, newdfd, new, flags);
6356 }
6357
SYSCALL_DEFINE4(renameat,int,olddfd,const char __user *,oldname,int,newdfd,const char __user *,newname)6358 SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
6359 int, newdfd, const char __user *, newname)
6360 {
6361 CLASS(filename, old)(oldname);
6362 CLASS(filename, new)(newname);
6363 return filename_renameat2(olddfd, old, newdfd, new, 0);
6364 }
6365
SYSCALL_DEFINE2(rename,const char __user *,oldname,const char __user *,newname)6366 SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
6367 {
6368 CLASS(filename, old)(oldname);
6369 CLASS(filename, new)(newname);
6370 return filename_renameat2(AT_FDCWD, old, AT_FDCWD, new, 0);
6371 }
6372
readlink_copy(char __user * buffer,int buflen,const char * link,int linklen)6373 int readlink_copy(char __user *buffer, int buflen, const char *link, int linklen)
6374 {
6375 int copylen;
6376
6377 copylen = linklen;
6378 if (unlikely(copylen > (unsigned) buflen))
6379 copylen = buflen;
6380 if (copy_to_user(buffer, link, copylen))
6381 copylen = -EFAULT;
6382 return copylen;
6383 }
6384
6385 /**
6386 * vfs_readlink - copy symlink body into userspace buffer
6387 * @dentry: dentry on which to get symbolic link
6388 * @buffer: user memory pointer
6389 * @buflen: size of buffer
6390 *
6391 * Does not touch atime. That's up to the caller if necessary
6392 *
6393 * Does not call security hook.
6394 */
vfs_readlink(struct dentry * dentry,char __user * buffer,int buflen)6395 int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen)
6396 {
6397 struct inode *inode = d_inode(dentry);
6398 DEFINE_DELAYED_CALL(done);
6399 const char *link;
6400 int res;
6401
6402 if (inode->i_opflags & IOP_CACHED_LINK)
6403 return readlink_copy(buffer, buflen, inode->i_link, inode->i_linklen);
6404
6405 if (unlikely(!(inode->i_opflags & IOP_DEFAULT_READLINK))) {
6406 if (unlikely(inode->i_op->readlink))
6407 return inode->i_op->readlink(dentry, buffer, buflen);
6408
6409 if (!d_is_symlink(dentry))
6410 return -EINVAL;
6411
6412 spin_lock(&inode->i_lock);
6413 inode->i_opflags |= IOP_DEFAULT_READLINK;
6414 spin_unlock(&inode->i_lock);
6415 }
6416
6417 link = READ_ONCE(inode->i_link);
6418 if (!link) {
6419 link = inode->i_op->get_link(dentry, inode, &done);
6420 if (IS_ERR(link))
6421 return PTR_ERR(link);
6422 }
6423 res = readlink_copy(buffer, buflen, link, strlen(link));
6424 do_delayed_call(&done);
6425 return res;
6426 }
6427 EXPORT_SYMBOL(vfs_readlink);
6428
6429 /**
6430 * vfs_get_link - get symlink body
6431 * @dentry: dentry on which to get symbolic link
6432 * @done: caller needs to free returned data with this
6433 *
6434 * Calls security hook and i_op->get_link() on the supplied inode.
6435 *
6436 * It does not touch atime. That's up to the caller if necessary.
6437 *
6438 * Does not work on "special" symlinks like /proc/$$/fd/N
6439 */
vfs_get_link(struct dentry * dentry,struct delayed_call * done)6440 const char *vfs_get_link(struct dentry *dentry, struct delayed_call *done)
6441 {
6442 const char *res = ERR_PTR(-EINVAL);
6443 struct inode *inode = d_inode(dentry);
6444
6445 if (d_is_symlink(dentry)) {
6446 res = ERR_PTR(security_inode_readlink(dentry));
6447 if (!res)
6448 res = inode->i_op->get_link(dentry, inode, done);
6449 }
6450 return res;
6451 }
6452 EXPORT_SYMBOL(vfs_get_link);
6453
6454 /* get the link contents into pagecache */
__page_get_link(struct dentry * dentry,struct inode * inode,struct delayed_call * callback)6455 static char *__page_get_link(struct dentry *dentry, struct inode *inode,
6456 struct delayed_call *callback)
6457 {
6458 struct folio *folio;
6459 struct address_space *mapping = inode->i_mapping;
6460
6461 if (!dentry) {
6462 folio = filemap_get_folio(mapping, 0);
6463 if (IS_ERR(folio))
6464 return ERR_PTR(-ECHILD);
6465 if (!folio_test_uptodate(folio)) {
6466 folio_put(folio);
6467 return ERR_PTR(-ECHILD);
6468 }
6469 } else {
6470 folio = read_mapping_folio(mapping, 0, NULL);
6471 if (IS_ERR(folio))
6472 return ERR_CAST(folio);
6473 }
6474 set_delayed_call(callback, page_put_link, folio);
6475 BUG_ON(mapping_gfp_mask(mapping) & __GFP_HIGHMEM);
6476 return folio_address(folio);
6477 }
6478
page_get_link_raw(struct dentry * dentry,struct inode * inode,struct delayed_call * callback)6479 const char *page_get_link_raw(struct dentry *dentry, struct inode *inode,
6480 struct delayed_call *callback)
6481 {
6482 return __page_get_link(dentry, inode, callback);
6483 }
6484 EXPORT_SYMBOL_GPL(page_get_link_raw);
6485
6486 /**
6487 * page_get_link() - An implementation of the get_link inode_operation.
6488 * @dentry: The directory entry which is the symlink.
6489 * @inode: The inode for the symlink.
6490 * @callback: Used to drop the reference to the symlink.
6491 *
6492 * Filesystems which store their symlinks in the page cache should use
6493 * this to implement the get_link() member of their inode_operations.
6494 *
6495 * Return: A pointer to the NUL-terminated symlink.
6496 */
page_get_link(struct dentry * dentry,struct inode * inode,struct delayed_call * callback)6497 const char *page_get_link(struct dentry *dentry, struct inode *inode,
6498 struct delayed_call *callback)
6499 {
6500 char *kaddr = __page_get_link(dentry, inode, callback);
6501
6502 if (!IS_ERR(kaddr))
6503 nd_terminate_link(kaddr, inode->i_size, PAGE_SIZE - 1);
6504 return kaddr;
6505 }
6506 EXPORT_SYMBOL(page_get_link);
6507
6508 /**
6509 * page_put_link() - Drop the reference to the symlink.
6510 * @arg: The folio which contains the symlink.
6511 *
6512 * This is used internally by page_get_link(). It is exported for use
6513 * by filesystems which need to implement a variant of page_get_link()
6514 * themselves. Despite the apparent symmetry, filesystems which use
6515 * page_get_link() do not need to call page_put_link().
6516 *
6517 * The argument, while it has a void pointer type, must be a pointer to
6518 * the folio which was retrieved from the page cache. The delayed_call
6519 * infrastructure is used to drop the reference count once the caller
6520 * is done with the symlink.
6521 */
page_put_link(void * arg)6522 void page_put_link(void *arg)
6523 {
6524 folio_put(arg);
6525 }
6526 EXPORT_SYMBOL(page_put_link);
6527
page_readlink(struct dentry * dentry,char __user * buffer,int buflen)6528 int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
6529 {
6530 const char *link;
6531 int res;
6532
6533 DEFINE_DELAYED_CALL(done);
6534 link = page_get_link(dentry, d_inode(dentry), &done);
6535 res = PTR_ERR(link);
6536 if (!IS_ERR(link))
6537 res = readlink_copy(buffer, buflen, link, strlen(link));
6538 do_delayed_call(&done);
6539 return res;
6540 }
6541 EXPORT_SYMBOL(page_readlink);
6542
page_symlink(struct inode * inode,const char * symname,int len)6543 int page_symlink(struct inode *inode, const char *symname, int len)
6544 {
6545 struct address_space *mapping = inode->i_mapping;
6546 const struct address_space_operations *aops = mapping->a_ops;
6547 bool nofs = !mapping_gfp_constraint(mapping, __GFP_FS);
6548 struct folio *folio;
6549 void *fsdata = NULL;
6550 int err;
6551 unsigned int flags;
6552
6553 retry:
6554 if (nofs)
6555 flags = memalloc_nofs_save();
6556 err = aops->write_begin(NULL, mapping, 0, len-1, &folio, &fsdata);
6557 if (nofs)
6558 memalloc_nofs_restore(flags);
6559 if (err)
6560 goto fail;
6561
6562 memcpy(folio_address(folio), symname, len - 1);
6563
6564 err = aops->write_end(NULL, mapping, 0, len - 1, len - 1,
6565 folio, fsdata);
6566 if (err < 0)
6567 goto fail;
6568 if (err < len-1)
6569 goto retry;
6570
6571 mark_inode_dirty(inode);
6572 return 0;
6573 fail:
6574 return err;
6575 }
6576 EXPORT_SYMBOL(page_symlink);
6577
6578 const struct inode_operations page_symlink_inode_operations = {
6579 .get_link = page_get_link,
6580 };
6581 EXPORT_SYMBOL(page_symlink_inode_operations);
6582