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