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