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