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