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