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