• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  linux/fs/namei.c
3  *
4  *  Copyright (C) 1991, 1992  Linus Torvalds
5  */
6 
7 /*
8  * Some corrections by tytso.
9  */
10 
11 /* [Feb 1997 T. Schoebel-Theuer] Complete rewrite of the pathname
12  * lookup logic.
13  */
14 /* [Feb-Apr 2000, AV] Rewrite to the new namespace architecture.
15  */
16 
17 #include <linux/init.h>
18 #include <linux/export.h>
19 #include <linux/kernel.h>
20 #include <linux/slab.h>
21 #include <linux/fs.h>
22 #include <linux/namei.h>
23 #include <linux/pagemap.h>
24 #include <linux/fsnotify.h>
25 #include <linux/personality.h>
26 #include <linux/security.h>
27 #include <linux/ima.h>
28 #include <linux/syscalls.h>
29 #include <linux/mount.h>
30 #include <linux/audit.h>
31 #include <linux/capability.h>
32 #include <linux/file.h>
33 #include <linux/fcntl.h>
34 #include <linux/device_cgroup.h>
35 #include <linux/fs_struct.h>
36 #include <linux/posix_acl.h>
37 #include <asm/uaccess.h>
38 
39 #include "internal.h"
40 #include "mount.h"
41 
42 /* [Feb-1997 T. Schoebel-Theuer]
43  * Fundamental changes in the pathname lookup mechanisms (namei)
44  * were necessary because of omirr.  The reason is that omirr needs
45  * to know the _real_ pathname, not the user-supplied one, in case
46  * of symlinks (and also when transname replacements occur).
47  *
48  * The new code replaces the old recursive symlink resolution with
49  * an iterative one (in case of non-nested symlink chains).  It does
50  * this with calls to <fs>_follow_link().
51  * As a side effect, dir_namei(), _namei() and follow_link() are now
52  * replaced with a single function lookup_dentry() that can handle all
53  * the special cases of the former code.
54  *
55  * With the new dcache, the pathname is stored at each inode, at least as
56  * long as the refcount of the inode is positive.  As a side effect, the
57  * size of the dcache depends on the inode cache and thus is dynamic.
58  *
59  * [29-Apr-1998 C. Scott Ananian] Updated above description of symlink
60  * resolution to correspond with current state of the code.
61  *
62  * Note that the symlink resolution is not *completely* iterative.
63  * There is still a significant amount of tail- and mid- recursion in
64  * the algorithm.  Also, note that <fs>_readlink() is not used in
65  * lookup_dentry(): lookup_dentry() on the result of <fs>_readlink()
66  * may return different results than <fs>_follow_link().  Many virtual
67  * filesystems (including /proc) exhibit this behavior.
68  */
69 
70 /* [24-Feb-97 T. Schoebel-Theuer] Side effects caused by new implementation:
71  * New symlink semantics: when open() is called with flags O_CREAT | O_EXCL
72  * and the name already exists in form of a symlink, try to create the new
73  * name indicated by the symlink. The old code always complained that the
74  * name already exists, due to not following the symlink even if its target
75  * is nonexistent.  The new semantics affects also mknod() and link() when
76  * the name is a symlink pointing to a non-existent name.
77  *
78  * I don't know which semantics is the right one, since I have no access
79  * to standards. But I found by trial that HP-UX 9.0 has the full "new"
80  * semantics implemented, while SunOS 4.1.1 and Solaris (SunOS 5.4) have the
81  * "old" one. Personally, I think the new semantics is much more logical.
82  * Note that "ln old new" where "new" is a symlink pointing to a non-existing
83  * file does succeed in both HP-UX and SunOs, but not in Solaris
84  * and in the old Linux semantics.
85  */
86 
87 /* [16-Dec-97 Kevin Buhr] For security reasons, we change some symlink
88  * semantics.  See the comments in "open_namei" and "do_link" below.
89  *
90  * [10-Sep-98 Alan Modra] Another symlink change.
91  */
92 
93 /* [Feb-Apr 2000 AV] Complete rewrite. Rules for symlinks:
94  *	inside the path - always follow.
95  *	in the last component in creation/removal/renaming - never follow.
96  *	if LOOKUP_FOLLOW passed - follow.
97  *	if the pathname has trailing slashes - follow.
98  *	otherwise - don't follow.
99  * (applied in that order).
100  *
101  * [Jun 2000 AV] Inconsistent behaviour of open() in case if flags==O_CREAT
102  * restored for 2.4. This is the last surviving part of old 4.2BSD bug.
103  * During the 2.4 we need to fix the userland stuff depending on it -
104  * hopefully we will be able to get rid of that wart in 2.5. So far only
105  * XEmacs seems to be relying on it...
106  */
107 /*
108  * [Sep 2001 AV] Single-semaphore locking scheme (kudos to David Holland)
109  * implemented.  Let's see if raised priority of ->s_vfs_rename_mutex gives
110  * any extra contention...
111  */
112 
113 /* In order to reduce some races, while at the same time doing additional
114  * checking and hopefully speeding things up, we copy filenames to the
115  * kernel data space before using them..
116  *
117  * POSIX.1 2.4: an empty pathname is invalid (ENOENT).
118  * PATH_MAX includes the nul terminator --RR.
119  */
final_putname(struct filename * name)120 void final_putname(struct filename *name)
121 {
122 	if (name->separate) {
123 		__putname(name->name);
124 		kfree(name);
125 	} else {
126 		__putname(name);
127 	}
128 }
129 
130 #define EMBEDDED_NAME_MAX	(PATH_MAX - sizeof(struct filename))
131 
132 static struct filename *
getname_flags(const char __user * filename,int flags,int * empty)133 getname_flags(const char __user *filename, int flags, int *empty)
134 {
135 	struct filename *result, *err;
136 	int len;
137 	long max;
138 	char *kname;
139 
140 	result = audit_reusename(filename);
141 	if (result)
142 		return result;
143 
144 	result = __getname();
145 	if (unlikely(!result))
146 		return ERR_PTR(-ENOMEM);
147 
148 	/*
149 	 * First, try to embed the struct filename inside the names_cache
150 	 * allocation
151 	 */
152 	kname = (char *)result + sizeof(*result);
153 	result->name = kname;
154 	result->separate = false;
155 	max = EMBEDDED_NAME_MAX;
156 
157 recopy:
158 	len = strncpy_from_user(kname, filename, max);
159 	if (unlikely(len < 0)) {
160 		err = ERR_PTR(len);
161 		goto error;
162 	}
163 
164 	/*
165 	 * Uh-oh. We have a name that's approaching PATH_MAX. Allocate a
166 	 * separate struct filename so we can dedicate the entire
167 	 * names_cache allocation for the pathname, and re-do the copy from
168 	 * userland.
169 	 */
170 	if (len == EMBEDDED_NAME_MAX && max == EMBEDDED_NAME_MAX) {
171 		kname = (char *)result;
172 
173 		result = kzalloc(sizeof(*result), GFP_KERNEL);
174 		if (!result) {
175 			err = ERR_PTR(-ENOMEM);
176 			result = (struct filename *)kname;
177 			goto error;
178 		}
179 		result->name = kname;
180 		result->separate = true;
181 		max = PATH_MAX;
182 		goto recopy;
183 	}
184 
185 	/* The empty path is special. */
186 	if (unlikely(!len)) {
187 		if (empty)
188 			*empty = 1;
189 		err = ERR_PTR(-ENOENT);
190 		if (!(flags & LOOKUP_EMPTY))
191 			goto error;
192 	}
193 
194 	err = ERR_PTR(-ENAMETOOLONG);
195 	if (unlikely(len >= PATH_MAX))
196 		goto error;
197 
198 	result->uptr = filename;
199 	audit_getname(result);
200 	return result;
201 
202 error:
203 	final_putname(result);
204 	return err;
205 }
206 
207 struct filename *
getname(const char __user * filename)208 getname(const char __user * filename)
209 {
210 	return getname_flags(filename, 0, NULL);
211 }
212 EXPORT_SYMBOL(getname);
213 
214 #ifdef CONFIG_AUDITSYSCALL
putname(struct filename * name)215 void putname(struct filename *name)
216 {
217 	if (unlikely(!audit_dummy_context()))
218 		return audit_putname(name);
219 	final_putname(name);
220 }
221 #endif
222 
check_acl(struct inode * inode,int mask)223 static int check_acl(struct inode *inode, int mask)
224 {
225 #ifdef CONFIG_FS_POSIX_ACL
226 	struct posix_acl *acl;
227 
228 	if (mask & MAY_NOT_BLOCK) {
229 		acl = get_cached_acl_rcu(inode, ACL_TYPE_ACCESS);
230 	        if (!acl)
231 	                return -EAGAIN;
232 		/* no ->get_acl() calls in RCU mode... */
233 		if (acl == ACL_NOT_CACHED)
234 			return -ECHILD;
235 	        return posix_acl_permission(inode, acl, mask & ~MAY_NOT_BLOCK);
236 	}
237 
238 	acl = get_cached_acl(inode, ACL_TYPE_ACCESS);
239 
240 	/*
241 	 * A filesystem can force a ACL callback by just never filling the
242 	 * ACL cache. But normally you'd fill the cache either at inode
243 	 * instantiation time, or on the first ->get_acl call.
244 	 *
245 	 * If the filesystem doesn't have a get_acl() function at all, we'll
246 	 * just create the negative cache entry.
247 	 */
248 	if (acl == ACL_NOT_CACHED) {
249 	        if (inode->i_op->get_acl) {
250 			acl = inode->i_op->get_acl(inode, ACL_TYPE_ACCESS);
251 			if (IS_ERR(acl))
252 				return PTR_ERR(acl);
253 		} else {
254 		        set_cached_acl(inode, ACL_TYPE_ACCESS, NULL);
255 		        return -EAGAIN;
256 		}
257 	}
258 
259 	if (acl) {
260 	        int error = posix_acl_permission(inode, acl, mask);
261 	        posix_acl_release(acl);
262 	        return error;
263 	}
264 #endif
265 
266 	return -EAGAIN;
267 }
268 
269 /*
270  * This does the basic permission checking
271  */
acl_permission_check(struct inode * inode,int mask)272 static int acl_permission_check(struct inode *inode, int mask)
273 {
274 	unsigned int mode = inode->i_mode;
275 
276 	if (likely(uid_eq(current_fsuid(), inode->i_uid)))
277 		mode >>= 6;
278 	else {
279 		if (IS_POSIXACL(inode) && (mode & S_IRWXG)) {
280 			int error = check_acl(inode, mask);
281 			if (error != -EAGAIN)
282 				return error;
283 		}
284 
285 		if (in_group_p(inode->i_gid))
286 			mode >>= 3;
287 	}
288 
289 	/*
290 	 * If the DACs are ok we don't need any capability check.
291 	 */
292 	if ((mask & ~mode & (MAY_READ | MAY_WRITE | MAY_EXEC)) == 0)
293 		return 0;
294 	return -EACCES;
295 }
296 
297 /**
298  * generic_permission -  check for access rights on a Posix-like filesystem
299  * @inode:	inode to check access rights for
300  * @mask:	right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC, ...)
301  *
302  * Used to check for read/write/execute permissions on a file.
303  * We use "fsuid" for this, letting us set arbitrary permissions
304  * for filesystem access without changing the "normal" uids which
305  * are used for other things.
306  *
307  * generic_permission is rcu-walk aware. It returns -ECHILD in case an rcu-walk
308  * request cannot be satisfied (eg. requires blocking or too much complexity).
309  * It would then be called again in ref-walk mode.
310  */
generic_permission(struct inode * inode,int mask)311 int generic_permission(struct inode *inode, int mask)
312 {
313 	int ret;
314 
315 	/*
316 	 * Do the basic permission checks.
317 	 */
318 	ret = acl_permission_check(inode, mask);
319 	if (ret != -EACCES)
320 		return ret;
321 
322 	if (S_ISDIR(inode->i_mode)) {
323 		/* DACs are overridable for directories */
324 		if (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE))
325 			return 0;
326 		if (!(mask & MAY_WRITE))
327 			if (capable_wrt_inode_uidgid(inode,
328 						     CAP_DAC_READ_SEARCH))
329 				return 0;
330 		return -EACCES;
331 	}
332 	/*
333 	 * Read/write DACs are always overridable.
334 	 * Executable DACs are overridable when there is
335 	 * at least one exec bit set.
336 	 */
337 	if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO))
338 		if (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE))
339 			return 0;
340 
341 	/*
342 	 * Searching includes executable on directories, else just read.
343 	 */
344 	mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
345 	if (mask == MAY_READ)
346 		if (capable_wrt_inode_uidgid(inode, CAP_DAC_READ_SEARCH))
347 			return 0;
348 
349 	return -EACCES;
350 }
351 
352 /*
353  * We _really_ want to just do "generic_permission()" without
354  * even looking at the inode->i_op values. So we keep a cache
355  * flag in inode->i_opflags, that says "this has not special
356  * permission function, use the fast case".
357  */
do_inode_permission(struct vfsmount * mnt,struct inode * inode,int mask)358 static inline int do_inode_permission(struct vfsmount *mnt, struct inode *inode, int mask)
359 {
360 	if (unlikely(!(inode->i_opflags & IOP_FASTPERM))) {
361 		if (likely(mnt && inode->i_op->permission2))
362 			return inode->i_op->permission2(mnt, inode, mask);
363 		if (likely(inode->i_op->permission))
364 			return inode->i_op->permission(inode, mask);
365 
366 		/* This gets set once for the inode lifetime */
367 		spin_lock(&inode->i_lock);
368 		inode->i_opflags |= IOP_FASTPERM;
369 		spin_unlock(&inode->i_lock);
370 	}
371 	return generic_permission(inode, mask);
372 }
373 
374 /**
375  * __inode_permission - Check for access rights to a given inode
376  * @inode: Inode to check permission on
377  * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
378  *
379  * Check for read/write/execute permissions on an inode.
380  *
381  * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask.
382  *
383  * This does not check for a read-only file system.  You probably want
384  * inode_permission().
385  */
__inode_permission2(struct vfsmount * mnt,struct inode * inode,int mask)386 int __inode_permission2(struct vfsmount *mnt, struct inode *inode, int mask)
387 {
388 	int retval;
389 
390 	if (unlikely(mask & MAY_WRITE)) {
391 		/*
392 		 * Nobody gets write access to an immutable file.
393 		 */
394 		if (IS_IMMUTABLE(inode))
395 			return -EACCES;
396 	}
397 
398 	retval = do_inode_permission(mnt, inode, mask);
399 	if (retval)
400 		return retval;
401 
402 	retval = devcgroup_inode_permission(inode, mask);
403 	if (retval)
404 		return retval;
405 
406 	return security_inode_permission(inode, mask);
407 }
408 EXPORT_SYMBOL(__inode_permission2);
409 
__inode_permission(struct inode * inode,int mask)410 int __inode_permission(struct inode *inode, int mask)
411 {
412 	return __inode_permission2(NULL, inode, mask);
413 }
414 EXPORT_SYMBOL(__inode_permission);
415 
416 /**
417  * sb_permission - Check superblock-level permissions
418  * @sb: Superblock of inode to check permission on
419  * @inode: Inode to check permission on
420  * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
421  *
422  * Separate out file-system wide checks from inode-specific permission checks.
423  */
sb_permission(struct super_block * sb,struct inode * inode,int mask)424 static int sb_permission(struct super_block *sb, struct inode *inode, int mask)
425 {
426 	if (unlikely(mask & MAY_WRITE)) {
427 		umode_t mode = inode->i_mode;
428 
429 		/* Nobody gets write access to a read-only fs. */
430 		if ((sb->s_flags & MS_RDONLY) &&
431 		    (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)))
432 			return -EROFS;
433 	}
434 	return 0;
435 }
436 
437 /**
438  * inode_permission - Check for access rights to a given inode
439  * @inode: Inode to check permission on
440  * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
441  *
442  * Check for read/write/execute permissions on an inode.  We use fs[ug]id for
443  * this, letting us set arbitrary permissions for filesystem access without
444  * changing the "normal" UIDs which are used for other things.
445  *
446  * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask.
447  */
inode_permission2(struct vfsmount * mnt,struct inode * inode,int mask)448 int inode_permission2(struct vfsmount *mnt, struct inode *inode, int mask)
449 {
450 	int retval;
451 
452 	retval = sb_permission(inode->i_sb, inode, mask);
453 	if (retval)
454 		return retval;
455 	return __inode_permission2(mnt, inode, mask);
456 }
457 EXPORT_SYMBOL(inode_permission2);
458 
inode_permission(struct inode * inode,int mask)459 int inode_permission(struct inode *inode, int mask)
460 {
461 	return inode_permission2(NULL, inode, mask);
462 }
463 EXPORT_SYMBOL(inode_permission);
464 
465 /**
466  * path_get - get a reference to a path
467  * @path: path to get the reference to
468  *
469  * Given a path increment the reference count to the dentry and the vfsmount.
470  */
path_get(const struct path * path)471 void path_get(const struct path *path)
472 {
473 	mntget(path->mnt);
474 	dget(path->dentry);
475 }
476 EXPORT_SYMBOL(path_get);
477 
478 /**
479  * path_put - put a reference to a path
480  * @path: path to put the reference to
481  *
482  * Given a path decrement the reference count to the dentry and the vfsmount.
483  */
path_put(const struct path * path)484 void path_put(const struct path *path)
485 {
486 	dput(path->dentry);
487 	mntput(path->mnt);
488 }
489 EXPORT_SYMBOL(path_put);
490 
491 /*
492  * Path walking has 2 modes, rcu-walk and ref-walk (see
493  * Documentation/filesystems/path-lookup.txt).  In situations when we can't
494  * continue in RCU mode, we attempt to drop out of rcu-walk mode and grab
495  * normal reference counts on dentries and vfsmounts to transition to rcu-walk
496  * mode.  Refcounts are grabbed at the last known good point before rcu-walk
497  * got stuck, so ref-walk may continue from there. If this is not successful
498  * (eg. a seqcount has changed), then failure is returned and it's up to caller
499  * to restart the path walk from the beginning in ref-walk mode.
500  */
501 
lock_rcu_walk(void)502 static inline void lock_rcu_walk(void)
503 {
504 	br_read_lock(&vfsmount_lock);
505 	rcu_read_lock();
506 }
507 
unlock_rcu_walk(void)508 static inline void unlock_rcu_walk(void)
509 {
510 	rcu_read_unlock();
511 	br_read_unlock(&vfsmount_lock);
512 }
513 
514 /**
515  * unlazy_walk - try to switch to ref-walk mode.
516  * @nd: nameidata pathwalk data
517  * @dentry: child of nd->path.dentry or NULL
518  * Returns: 0 on success, -ECHILD on failure
519  *
520  * unlazy_walk attempts to legitimize the current nd->path, nd->root and dentry
521  * for ref-walk mode.  @dentry must be a path found by a do_lookup call on
522  * @nd or NULL.  Must be called from rcu-walk context.
523  */
unlazy_walk(struct nameidata * nd,struct dentry * dentry)524 static int unlazy_walk(struct nameidata *nd, struct dentry *dentry)
525 {
526 	struct fs_struct *fs = current->fs;
527 	struct dentry *parent = nd->path.dentry;
528 	int want_root = 0;
529 
530 	BUG_ON(!(nd->flags & LOOKUP_RCU));
531 	if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT)) {
532 		want_root = 1;
533 		spin_lock(&fs->lock);
534 		if (nd->root.mnt != fs->root.mnt ||
535 				nd->root.dentry != fs->root.dentry)
536 			goto err_root;
537 	}
538 	spin_lock(&parent->d_lock);
539 	if (!dentry) {
540 		if (!__d_rcu_to_refcount(parent, nd->seq))
541 			goto err_parent;
542 		BUG_ON(nd->inode != parent->d_inode);
543 	} else {
544 		if (dentry->d_parent != parent)
545 			goto err_parent;
546 		spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
547 		if (!__d_rcu_to_refcount(dentry, nd->seq))
548 			goto err_child;
549 		/*
550 		 * If the sequence check on the child dentry passed, then
551 		 * the child has not been removed from its parent. This
552 		 * means the parent dentry must be valid and able to take
553 		 * a reference at this point.
554 		 */
555 		BUG_ON(!IS_ROOT(dentry) && dentry->d_parent != parent);
556 		BUG_ON(!parent->d_count);
557 		parent->d_count++;
558 		spin_unlock(&dentry->d_lock);
559 	}
560 	spin_unlock(&parent->d_lock);
561 	if (want_root) {
562 		path_get(&nd->root);
563 		spin_unlock(&fs->lock);
564 	}
565 	mntget(nd->path.mnt);
566 
567 	unlock_rcu_walk();
568 	nd->flags &= ~LOOKUP_RCU;
569 	return 0;
570 
571 err_child:
572 	spin_unlock(&dentry->d_lock);
573 err_parent:
574 	spin_unlock(&parent->d_lock);
575 err_root:
576 	if (want_root)
577 		spin_unlock(&fs->lock);
578 	return -ECHILD;
579 }
580 
d_revalidate(struct dentry * dentry,unsigned int flags)581 static inline int d_revalidate(struct dentry *dentry, unsigned int flags)
582 {
583 	return dentry->d_op->d_revalidate(dentry, flags);
584 }
585 
586 /**
587  * complete_walk - successful completion of path walk
588  * @nd:  pointer nameidata
589  *
590  * If we had been in RCU mode, drop out of it and legitimize nd->path.
591  * Revalidate the final result, unless we'd already done that during
592  * the path walk or the filesystem doesn't ask for it.  Return 0 on
593  * success, -error on failure.  In case of failure caller does not
594  * need to drop nd->path.
595  */
complete_walk(struct nameidata * nd)596 static int complete_walk(struct nameidata *nd)
597 {
598 	struct dentry *dentry = nd->path.dentry;
599 	int status;
600 
601 	if (nd->flags & LOOKUP_RCU) {
602 		nd->flags &= ~LOOKUP_RCU;
603 		if (!(nd->flags & LOOKUP_ROOT))
604 			nd->root.mnt = NULL;
605 		spin_lock(&dentry->d_lock);
606 		if (unlikely(!__d_rcu_to_refcount(dentry, nd->seq))) {
607 			spin_unlock(&dentry->d_lock);
608 			unlock_rcu_walk();
609 			return -ECHILD;
610 		}
611 		BUG_ON(nd->inode != dentry->d_inode);
612 		spin_unlock(&dentry->d_lock);
613 		mntget(nd->path.mnt);
614 		unlock_rcu_walk();
615 	}
616 
617 	if (likely(!(nd->flags & LOOKUP_JUMPED)))
618 		return 0;
619 
620 	if (likely(!(dentry->d_flags & DCACHE_OP_WEAK_REVALIDATE)))
621 		return 0;
622 
623 	status = dentry->d_op->d_weak_revalidate(dentry, nd->flags);
624 	if (status > 0)
625 		return 0;
626 
627 	if (!status)
628 		status = -ESTALE;
629 
630 	path_put(&nd->path);
631 	return status;
632 }
633 
set_root(struct nameidata * nd)634 static __always_inline void set_root(struct nameidata *nd)
635 {
636 	if (!nd->root.mnt)
637 		get_fs_root(current->fs, &nd->root);
638 }
639 
640 static int link_path_walk(const char *, struct nameidata *);
641 
set_root_rcu(struct nameidata * nd)642 static __always_inline void set_root_rcu(struct nameidata *nd)
643 {
644 	if (!nd->root.mnt) {
645 		struct fs_struct *fs = current->fs;
646 		unsigned seq;
647 
648 		do {
649 			seq = read_seqcount_begin(&fs->seq);
650 			nd->root = fs->root;
651 			nd->seq = __read_seqcount_begin(&nd->root.dentry->d_seq);
652 		} while (read_seqcount_retry(&fs->seq, seq));
653 	}
654 }
655 
__vfs_follow_link(struct nameidata * nd,const char * link)656 static __always_inline int __vfs_follow_link(struct nameidata *nd, const char *link)
657 {
658 	int ret;
659 
660 	if (IS_ERR(link))
661 		goto fail;
662 
663 	if (*link == '/') {
664 		set_root(nd);
665 		path_put(&nd->path);
666 		nd->path = nd->root;
667 		path_get(&nd->root);
668 		nd->flags |= LOOKUP_JUMPED;
669 	}
670 	nd->inode = nd->path.dentry->d_inode;
671 
672 	ret = link_path_walk(link, nd);
673 	return ret;
674 fail:
675 	path_put(&nd->path);
676 	return PTR_ERR(link);
677 }
678 
path_put_conditional(struct path * path,struct nameidata * nd)679 static void path_put_conditional(struct path *path, struct nameidata *nd)
680 {
681 	dput(path->dentry);
682 	if (path->mnt != nd->path.mnt)
683 		mntput(path->mnt);
684 }
685 
path_to_nameidata(const struct path * path,struct nameidata * nd)686 static inline void path_to_nameidata(const struct path *path,
687 					struct nameidata *nd)
688 {
689 	if (!(nd->flags & LOOKUP_RCU)) {
690 		dput(nd->path.dentry);
691 		if (nd->path.mnt != path->mnt)
692 			mntput(nd->path.mnt);
693 	}
694 	nd->path.mnt = path->mnt;
695 	nd->path.dentry = path->dentry;
696 }
697 
698 /*
699  * Helper to directly jump to a known parsed path from ->follow_link,
700  * caller must have taken a reference to path beforehand.
701  */
nd_jump_link(struct nameidata * nd,struct path * path)702 void nd_jump_link(struct nameidata *nd, struct path *path)
703 {
704 	path_put(&nd->path);
705 
706 	nd->path = *path;
707 	nd->inode = nd->path.dentry->d_inode;
708 	nd->flags |= LOOKUP_JUMPED;
709 }
710 
put_link(struct nameidata * nd,struct path * link,void * cookie)711 static inline void put_link(struct nameidata *nd, struct path *link, void *cookie)
712 {
713 	struct inode *inode = link->dentry->d_inode;
714 	if (inode->i_op->put_link)
715 		inode->i_op->put_link(link->dentry, nd, cookie);
716 	path_put(link);
717 }
718 
719 int sysctl_protected_symlinks __read_mostly = 0;
720 int sysctl_protected_hardlinks __read_mostly = 0;
721 
722 /**
723  * may_follow_link - Check symlink following for unsafe situations
724  * @link: The path of the symlink
725  * @nd: nameidata pathwalk data
726  *
727  * In the case of the sysctl_protected_symlinks sysctl being enabled,
728  * CAP_DAC_OVERRIDE needs to be specifically ignored if the symlink is
729  * in a sticky world-writable directory. This is to protect privileged
730  * processes from failing races against path names that may change out
731  * from under them by way of other users creating malicious symlinks.
732  * It will permit symlinks to be followed only when outside a sticky
733  * world-writable directory, or when the uid of the symlink and follower
734  * match, or when the directory owner matches the symlink's owner.
735  *
736  * Returns 0 if following the symlink is allowed, -ve on error.
737  */
may_follow_link(struct path * link,struct nameidata * nd)738 static inline int may_follow_link(struct path *link, struct nameidata *nd)
739 {
740 	const struct inode *inode;
741 	const struct inode *parent;
742 
743 	if (!sysctl_protected_symlinks)
744 		return 0;
745 
746 	/* Allowed if owner and follower match. */
747 	inode = link->dentry->d_inode;
748 	if (uid_eq(current_cred()->fsuid, inode->i_uid))
749 		return 0;
750 
751 	/* Allowed if parent directory not sticky and world-writable. */
752 	parent = nd->path.dentry->d_inode;
753 	if ((parent->i_mode & (S_ISVTX|S_IWOTH)) != (S_ISVTX|S_IWOTH))
754 		return 0;
755 
756 	/* Allowed if parent directory and link owner match. */
757 	if (uid_eq(parent->i_uid, inode->i_uid))
758 		return 0;
759 
760 	audit_log_link_denied("follow_link", link);
761 	path_put_conditional(link, nd);
762 	path_put(&nd->path);
763 	return -EACCES;
764 }
765 
766 /**
767  * safe_hardlink_source - Check for safe hardlink conditions
768  * @inode: the source inode to hardlink from
769  *
770  * Return false if at least one of the following conditions:
771  *    - inode is not a regular file
772  *    - inode is setuid
773  *    - inode is setgid and group-exec
774  *    - access failure for read and write
775  *
776  * Otherwise returns true.
777  */
safe_hardlink_source(struct inode * inode)778 static bool safe_hardlink_source(struct inode *inode)
779 {
780 	umode_t mode = inode->i_mode;
781 
782 	/* Special files should not get pinned to the filesystem. */
783 	if (!S_ISREG(mode))
784 		return false;
785 
786 	/* Setuid files should not get pinned to the filesystem. */
787 	if (mode & S_ISUID)
788 		return false;
789 
790 	/* Executable setgid files should not get pinned to the filesystem. */
791 	if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
792 		return false;
793 
794 	/* Hardlinking to unreadable or unwritable sources is dangerous. */
795 	if (inode_permission(inode, MAY_READ | MAY_WRITE))
796 		return false;
797 
798 	return true;
799 }
800 
801 /**
802  * may_linkat - Check permissions for creating a hardlink
803  * @link: the source to hardlink from
804  *
805  * Block hardlink when all of:
806  *  - sysctl_protected_hardlinks enabled
807  *  - fsuid does not match inode
808  *  - hardlink source is unsafe (see safe_hardlink_source() above)
809  *  - not CAP_FOWNER
810  *
811  * Returns 0 if successful, -ve on error.
812  */
may_linkat(struct path * link)813 static int may_linkat(struct path *link)
814 {
815 	const struct cred *cred;
816 	struct inode *inode;
817 
818 	if (!sysctl_protected_hardlinks)
819 		return 0;
820 
821 	cred = current_cred();
822 	inode = link->dentry->d_inode;
823 
824 	/* Source inode owner (or CAP_FOWNER) can hardlink all they like,
825 	 * otherwise, it must be a safe source.
826 	 */
827 	if (uid_eq(cred->fsuid, inode->i_uid) || safe_hardlink_source(inode) ||
828 	    capable(CAP_FOWNER))
829 		return 0;
830 
831 	audit_log_link_denied("linkat", link);
832 	return -EPERM;
833 }
834 
835 static __always_inline int
follow_link(struct path * link,struct nameidata * nd,void ** p)836 follow_link(struct path *link, struct nameidata *nd, void **p)
837 {
838 	struct dentry *dentry = link->dentry;
839 	int error;
840 	char *s;
841 
842 	BUG_ON(nd->flags & LOOKUP_RCU);
843 
844 	if (link->mnt == nd->path.mnt)
845 		mntget(link->mnt);
846 
847 	error = -ELOOP;
848 	if (unlikely(current->total_link_count >= 40))
849 		goto out_put_nd_path;
850 
851 	cond_resched();
852 	current->total_link_count++;
853 
854 	touch_atime(link);
855 	nd_set_link(nd, NULL);
856 
857 	error = security_inode_follow_link(link->dentry, nd);
858 	if (error)
859 		goto out_put_nd_path;
860 
861 	nd->last_type = LAST_BIND;
862 	*p = dentry->d_inode->i_op->follow_link(dentry, nd);
863 	error = PTR_ERR(*p);
864 	if (IS_ERR(*p))
865 		goto out_put_nd_path;
866 
867 	error = 0;
868 	s = nd_get_link(nd);
869 	if (s) {
870 		error = __vfs_follow_link(nd, s);
871 		if (unlikely(error))
872 			put_link(nd, link, *p);
873 	}
874 
875 	return error;
876 
877 out_put_nd_path:
878 	*p = NULL;
879 	path_put(&nd->path);
880 	path_put(link);
881 	return error;
882 }
883 
follow_up_rcu(struct path * path)884 static int follow_up_rcu(struct path *path)
885 {
886 	struct mount *mnt = real_mount(path->mnt);
887 	struct mount *parent;
888 	struct dentry *mountpoint;
889 
890 	parent = mnt->mnt_parent;
891 	if (&parent->mnt == path->mnt)
892 		return 0;
893 	mountpoint = mnt->mnt_mountpoint;
894 	path->dentry = mountpoint;
895 	path->mnt = &parent->mnt;
896 	return 1;
897 }
898 
899 /*
900  * follow_up - Find the mountpoint of path's vfsmount
901  *
902  * Given a path, find the mountpoint of its source file system.
903  * Replace @path with the path of the mountpoint in the parent mount.
904  * Up is towards /.
905  *
906  * Return 1 if we went up a level and 0 if we were already at the
907  * root.
908  */
follow_up(struct path * path)909 int follow_up(struct path *path)
910 {
911 	struct mount *mnt = real_mount(path->mnt);
912 	struct mount *parent;
913 	struct dentry *mountpoint;
914 
915 	br_read_lock(&vfsmount_lock);
916 	parent = mnt->mnt_parent;
917 	if (parent == mnt) {
918 		br_read_unlock(&vfsmount_lock);
919 		return 0;
920 	}
921 	mntget(&parent->mnt);
922 	mountpoint = dget(mnt->mnt_mountpoint);
923 	br_read_unlock(&vfsmount_lock);
924 	dput(path->dentry);
925 	path->dentry = mountpoint;
926 	mntput(path->mnt);
927 	path->mnt = &parent->mnt;
928 	return 1;
929 }
930 
931 /*
932  * Perform an automount
933  * - return -EISDIR to tell follow_managed() to stop and return the path we
934  *   were called with.
935  */
follow_automount(struct path * path,unsigned flags,bool * need_mntput)936 static int follow_automount(struct path *path, unsigned flags,
937 			    bool *need_mntput)
938 {
939 	struct vfsmount *mnt;
940 	int err;
941 
942 	if (!path->dentry->d_op || !path->dentry->d_op->d_automount)
943 		return -EREMOTE;
944 
945 	/* We don't want to mount if someone's just doing a stat -
946 	 * unless they're stat'ing a directory and appended a '/' to
947 	 * the name.
948 	 *
949 	 * We do, however, want to mount if someone wants to open or
950 	 * create a file of any type under the mountpoint, wants to
951 	 * traverse through the mountpoint or wants to open the
952 	 * mounted directory.  Also, autofs may mark negative dentries
953 	 * as being automount points.  These will need the attentions
954 	 * of the daemon to instantiate them before they can be used.
955 	 */
956 	if (!(flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY |
957 		     LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) &&
958 	    path->dentry->d_inode)
959 		return -EISDIR;
960 
961 	current->total_link_count++;
962 	if (current->total_link_count >= 40)
963 		return -ELOOP;
964 
965 	mnt = path->dentry->d_op->d_automount(path);
966 	if (IS_ERR(mnt)) {
967 		/*
968 		 * The filesystem is allowed to return -EISDIR here to indicate
969 		 * it doesn't want to automount.  For instance, autofs would do
970 		 * this so that its userspace daemon can mount on this dentry.
971 		 *
972 		 * However, we can only permit this if it's a terminal point in
973 		 * the path being looked up; if it wasn't then the remainder of
974 		 * the path is inaccessible and we should say so.
975 		 */
976 		if (PTR_ERR(mnt) == -EISDIR && (flags & LOOKUP_PARENT))
977 			return -EREMOTE;
978 		return PTR_ERR(mnt);
979 	}
980 
981 	if (!mnt) /* mount collision */
982 		return 0;
983 
984 	if (!*need_mntput) {
985 		/* lock_mount() may release path->mnt on error */
986 		mntget(path->mnt);
987 		*need_mntput = true;
988 	}
989 	err = finish_automount(mnt, path);
990 
991 	switch (err) {
992 	case -EBUSY:
993 		/* Someone else made a mount here whilst we were busy */
994 		return 0;
995 	case 0:
996 		path_put(path);
997 		path->mnt = mnt;
998 		path->dentry = dget(mnt->mnt_root);
999 		return 0;
1000 	default:
1001 		return err;
1002 	}
1003 
1004 }
1005 
1006 /*
1007  * Handle a dentry that is managed in some way.
1008  * - Flagged for transit management (autofs)
1009  * - Flagged as mountpoint
1010  * - Flagged as automount point
1011  *
1012  * This may only be called in refwalk mode.
1013  *
1014  * Serialization is taken care of in namespace.c
1015  */
follow_managed(struct path * path,unsigned flags)1016 static int follow_managed(struct path *path, unsigned flags)
1017 {
1018 	struct vfsmount *mnt = path->mnt; /* held by caller, must be left alone */
1019 	unsigned managed;
1020 	bool need_mntput = false;
1021 	int ret = 0;
1022 
1023 	/* Given that we're not holding a lock here, we retain the value in a
1024 	 * local variable for each dentry as we look at it so that we don't see
1025 	 * the components of that value change under us */
1026 	while (managed = ACCESS_ONCE(path->dentry->d_flags),
1027 	       managed &= DCACHE_MANAGED_DENTRY,
1028 	       unlikely(managed != 0)) {
1029 		/* Allow the filesystem to manage the transit without i_mutex
1030 		 * being held. */
1031 		if (managed & DCACHE_MANAGE_TRANSIT) {
1032 			BUG_ON(!path->dentry->d_op);
1033 			BUG_ON(!path->dentry->d_op->d_manage);
1034 			ret = path->dentry->d_op->d_manage(path->dentry, false);
1035 			if (ret < 0)
1036 				break;
1037 		}
1038 
1039 		/* Transit to a mounted filesystem. */
1040 		if (managed & DCACHE_MOUNTED) {
1041 			struct vfsmount *mounted = lookup_mnt(path);
1042 			if (mounted) {
1043 				dput(path->dentry);
1044 				if (need_mntput)
1045 					mntput(path->mnt);
1046 				path->mnt = mounted;
1047 				path->dentry = dget(mounted->mnt_root);
1048 				need_mntput = true;
1049 				continue;
1050 			}
1051 
1052 			/* Something is mounted on this dentry in another
1053 			 * namespace and/or whatever was mounted there in this
1054 			 * namespace got unmounted before we managed to get the
1055 			 * vfsmount_lock */
1056 		}
1057 
1058 		/* Handle an automount point */
1059 		if (managed & DCACHE_NEED_AUTOMOUNT) {
1060 			ret = follow_automount(path, flags, &need_mntput);
1061 			if (ret < 0)
1062 				break;
1063 			continue;
1064 		}
1065 
1066 		/* We didn't change the current path point */
1067 		break;
1068 	}
1069 
1070 	if (need_mntput && path->mnt == mnt)
1071 		mntput(path->mnt);
1072 	if (ret == -EISDIR)
1073 		ret = 0;
1074 	return ret < 0 ? ret : need_mntput;
1075 }
1076 
follow_down_one(struct path * path)1077 int follow_down_one(struct path *path)
1078 {
1079 	struct vfsmount *mounted;
1080 
1081 	mounted = lookup_mnt(path);
1082 	if (mounted) {
1083 		dput(path->dentry);
1084 		mntput(path->mnt);
1085 		path->mnt = mounted;
1086 		path->dentry = dget(mounted->mnt_root);
1087 		return 1;
1088 	}
1089 	return 0;
1090 }
1091 
managed_dentry_might_block(struct dentry * dentry)1092 static inline bool managed_dentry_might_block(struct dentry *dentry)
1093 {
1094 	return (dentry->d_flags & DCACHE_MANAGE_TRANSIT &&
1095 		dentry->d_op->d_manage(dentry, true) < 0);
1096 }
1097 
1098 /*
1099  * Try to skip to top of mountpoint pile in rcuwalk mode.  Fail if
1100  * we meet a managed dentry that would need blocking.
1101  */
__follow_mount_rcu(struct nameidata * nd,struct path * path,struct inode ** inode)1102 static bool __follow_mount_rcu(struct nameidata *nd, struct path *path,
1103 			       struct inode **inode)
1104 {
1105 	for (;;) {
1106 		struct mount *mounted;
1107 		/*
1108 		 * Don't forget we might have a non-mountpoint managed dentry
1109 		 * that wants to block transit.
1110 		 */
1111 		if (unlikely(managed_dentry_might_block(path->dentry)))
1112 			return false;
1113 
1114 		if (!d_mountpoint(path->dentry))
1115 			break;
1116 
1117 		mounted = __lookup_mnt(path->mnt, path->dentry, 1);
1118 		if (!mounted)
1119 			break;
1120 		path->mnt = &mounted->mnt;
1121 		path->dentry = mounted->mnt.mnt_root;
1122 		nd->flags |= LOOKUP_JUMPED;
1123 		nd->seq = read_seqcount_begin(&path->dentry->d_seq);
1124 		/*
1125 		 * Update the inode too. We don't need to re-check the
1126 		 * dentry sequence number here after this d_inode read,
1127 		 * because a mount-point is always pinned.
1128 		 */
1129 		*inode = path->dentry->d_inode;
1130 	}
1131 	return true;
1132 }
1133 
follow_mount_rcu(struct nameidata * nd)1134 static void follow_mount_rcu(struct nameidata *nd)
1135 {
1136 	while (d_mountpoint(nd->path.dentry)) {
1137 		struct mount *mounted;
1138 		mounted = __lookup_mnt(nd->path.mnt, nd->path.dentry, 1);
1139 		if (!mounted)
1140 			break;
1141 		nd->path.mnt = &mounted->mnt;
1142 		nd->path.dentry = mounted->mnt.mnt_root;
1143 		nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
1144 	}
1145 }
1146 
follow_dotdot_rcu(struct nameidata * nd)1147 static int follow_dotdot_rcu(struct nameidata *nd)
1148 {
1149 	set_root_rcu(nd);
1150 
1151 	while (1) {
1152 		if (nd->path.dentry == nd->root.dentry &&
1153 		    nd->path.mnt == nd->root.mnt) {
1154 			break;
1155 		}
1156 		if (nd->path.dentry != nd->path.mnt->mnt_root) {
1157 			struct dentry *old = nd->path.dentry;
1158 			struct dentry *parent = old->d_parent;
1159 			unsigned seq;
1160 
1161 			seq = read_seqcount_begin(&parent->d_seq);
1162 			if (read_seqcount_retry(&old->d_seq, nd->seq))
1163 				goto failed;
1164 			nd->path.dentry = parent;
1165 			nd->seq = seq;
1166 			break;
1167 		}
1168 		if (!follow_up_rcu(&nd->path))
1169 			break;
1170 		nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
1171 	}
1172 	follow_mount_rcu(nd);
1173 	nd->inode = nd->path.dentry->d_inode;
1174 	return 0;
1175 
1176 failed:
1177 	nd->flags &= ~LOOKUP_RCU;
1178 	if (!(nd->flags & LOOKUP_ROOT))
1179 		nd->root.mnt = NULL;
1180 	unlock_rcu_walk();
1181 	return -ECHILD;
1182 }
1183 
1184 /*
1185  * Follow down to the covering mount currently visible to userspace.  At each
1186  * point, the filesystem owning that dentry may be queried as to whether the
1187  * caller is permitted to proceed or not.
1188  */
follow_down(struct path * path)1189 int follow_down(struct path *path)
1190 {
1191 	unsigned managed;
1192 	int ret;
1193 
1194 	while (managed = ACCESS_ONCE(path->dentry->d_flags),
1195 	       unlikely(managed & DCACHE_MANAGED_DENTRY)) {
1196 		/* Allow the filesystem to manage the transit without i_mutex
1197 		 * being held.
1198 		 *
1199 		 * We indicate to the filesystem if someone is trying to mount
1200 		 * something here.  This gives autofs the chance to deny anyone
1201 		 * other than its daemon the right to mount on its
1202 		 * superstructure.
1203 		 *
1204 		 * The filesystem may sleep at this point.
1205 		 */
1206 		if (managed & DCACHE_MANAGE_TRANSIT) {
1207 			BUG_ON(!path->dentry->d_op);
1208 			BUG_ON(!path->dentry->d_op->d_manage);
1209 			ret = path->dentry->d_op->d_manage(
1210 				path->dentry, false);
1211 			if (ret < 0)
1212 				return ret == -EISDIR ? 0 : ret;
1213 		}
1214 
1215 		/* Transit to a mounted filesystem. */
1216 		if (managed & DCACHE_MOUNTED) {
1217 			struct vfsmount *mounted = lookup_mnt(path);
1218 			if (!mounted)
1219 				break;
1220 			dput(path->dentry);
1221 			mntput(path->mnt);
1222 			path->mnt = mounted;
1223 			path->dentry = dget(mounted->mnt_root);
1224 			continue;
1225 		}
1226 
1227 		/* Don't handle automount points here */
1228 		break;
1229 	}
1230 	return 0;
1231 }
1232 
1233 /*
1234  * Skip to top of mountpoint pile in refwalk mode for follow_dotdot()
1235  */
follow_mount(struct path * path)1236 static void follow_mount(struct path *path)
1237 {
1238 	while (d_mountpoint(path->dentry)) {
1239 		struct vfsmount *mounted = lookup_mnt(path);
1240 		if (!mounted)
1241 			break;
1242 		dput(path->dentry);
1243 		mntput(path->mnt);
1244 		path->mnt = mounted;
1245 		path->dentry = dget(mounted->mnt_root);
1246 	}
1247 }
1248 
follow_dotdot(struct nameidata * nd)1249 static void follow_dotdot(struct nameidata *nd)
1250 {
1251 	set_root(nd);
1252 
1253 	while(1) {
1254 		struct dentry *old = nd->path.dentry;
1255 
1256 		if (nd->path.dentry == nd->root.dentry &&
1257 		    nd->path.mnt == nd->root.mnt) {
1258 			break;
1259 		}
1260 		if (nd->path.dentry != nd->path.mnt->mnt_root) {
1261 			/* rare case of legitimate dget_parent()... */
1262 			nd->path.dentry = dget_parent(nd->path.dentry);
1263 			dput(old);
1264 			break;
1265 		}
1266 		if (!follow_up(&nd->path))
1267 			break;
1268 	}
1269 	follow_mount(&nd->path);
1270 	nd->inode = nd->path.dentry->d_inode;
1271 }
1272 
1273 /*
1274  * This looks up the name in dcache, possibly revalidates the old dentry and
1275  * allocates a new one if not found or not valid.  In the need_lookup argument
1276  * returns whether i_op->lookup is necessary.
1277  *
1278  * dir->d_inode->i_mutex must be held
1279  */
lookup_dcache(struct qstr * name,struct dentry * dir,unsigned int flags,bool * need_lookup)1280 static struct dentry *lookup_dcache(struct qstr *name, struct dentry *dir,
1281 				    unsigned int flags, bool *need_lookup)
1282 {
1283 	struct dentry *dentry;
1284 	int error;
1285 
1286 	*need_lookup = false;
1287 	dentry = d_lookup(dir, name);
1288 	if (dentry) {
1289 		if (dentry->d_flags & DCACHE_OP_REVALIDATE) {
1290 			error = d_revalidate(dentry, flags);
1291 			if (unlikely(error <= 0)) {
1292 				if (error < 0) {
1293 					dput(dentry);
1294 					return ERR_PTR(error);
1295 				} else if (!d_invalidate(dentry)) {
1296 					dput(dentry);
1297 					dentry = NULL;
1298 				}
1299 			}
1300 		}
1301 	}
1302 
1303 	if (!dentry) {
1304 		dentry = d_alloc(dir, name);
1305 		if (unlikely(!dentry))
1306 			return ERR_PTR(-ENOMEM);
1307 
1308 		*need_lookup = true;
1309 	}
1310 	return dentry;
1311 }
1312 
1313 /*
1314  * Call i_op->lookup on the dentry.  The dentry must be negative but may be
1315  * hashed if it was pouplated with DCACHE_NEED_LOOKUP.
1316  *
1317  * dir->d_inode->i_mutex must be held
1318  */
lookup_real(struct inode * dir,struct dentry * dentry,unsigned int flags)1319 static struct dentry *lookup_real(struct inode *dir, struct dentry *dentry,
1320 				  unsigned int flags)
1321 {
1322 	struct dentry *old;
1323 
1324 	/* Don't create child dentry for a dead directory. */
1325 	if (unlikely(IS_DEADDIR(dir))) {
1326 		dput(dentry);
1327 		return ERR_PTR(-ENOENT);
1328 	}
1329 
1330 	old = dir->i_op->lookup(dir, dentry, flags);
1331 	if (unlikely(old)) {
1332 		dput(dentry);
1333 		dentry = old;
1334 	}
1335 	return dentry;
1336 }
1337 
__lookup_hash(struct qstr * name,struct dentry * base,unsigned int flags)1338 static struct dentry *__lookup_hash(struct qstr *name,
1339 		struct dentry *base, unsigned int flags)
1340 {
1341 	bool need_lookup;
1342 	struct dentry *dentry;
1343 
1344 	dentry = lookup_dcache(name, base, flags, &need_lookup);
1345 	if (!need_lookup)
1346 		return dentry;
1347 
1348 	return lookup_real(base->d_inode, dentry, flags);
1349 }
1350 
1351 /*
1352  *  It's more convoluted than I'd like it to be, but... it's still fairly
1353  *  small and for now I'd prefer to have fast path as straight as possible.
1354  *  It _is_ time-critical.
1355  */
lookup_fast(struct nameidata * nd,struct path * path,struct inode ** inode)1356 static int lookup_fast(struct nameidata *nd,
1357 		       struct path *path, struct inode **inode)
1358 {
1359 	struct vfsmount *mnt = nd->path.mnt;
1360 	struct dentry *dentry, *parent = nd->path.dentry;
1361 	int need_reval = 1;
1362 	int status = 1;
1363 	int err;
1364 
1365 	/*
1366 	 * Rename seqlock is not required here because in the off chance
1367 	 * of a false negative due to a concurrent rename, we're going to
1368 	 * do the non-racy lookup, below.
1369 	 */
1370 	if (nd->flags & LOOKUP_RCU) {
1371 		unsigned seq;
1372 		dentry = __d_lookup_rcu(parent, &nd->last, &seq, nd->inode);
1373 		if (!dentry)
1374 			goto unlazy;
1375 
1376 		/*
1377 		 * This sequence count validates that the inode matches
1378 		 * the dentry name information from lookup.
1379 		 */
1380 		*inode = dentry->d_inode;
1381 		if (read_seqcount_retry(&dentry->d_seq, seq))
1382 			return -ECHILD;
1383 
1384 		/*
1385 		 * This sequence count validates that the parent had no
1386 		 * changes while we did the lookup of the dentry above.
1387 		 *
1388 		 * The memory barrier in read_seqcount_begin of child is
1389 		 *  enough, we can use __read_seqcount_retry here.
1390 		 */
1391 		if (__read_seqcount_retry(&parent->d_seq, nd->seq))
1392 			return -ECHILD;
1393 		nd->seq = seq;
1394 
1395 		if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE)) {
1396 			status = d_revalidate(dentry, nd->flags);
1397 			if (unlikely(status <= 0)) {
1398 				if (status != -ECHILD)
1399 					need_reval = 0;
1400 				goto unlazy;
1401 			}
1402 		}
1403 		path->mnt = mnt;
1404 		path->dentry = dentry;
1405 		if (unlikely(!__follow_mount_rcu(nd, path, inode)))
1406 			goto unlazy;
1407 		if (unlikely(path->dentry->d_flags & DCACHE_NEED_AUTOMOUNT))
1408 			goto unlazy;
1409 		return 0;
1410 unlazy:
1411 		if (unlazy_walk(nd, dentry))
1412 			return -ECHILD;
1413 	} else {
1414 		dentry = __d_lookup(parent, &nd->last);
1415 	}
1416 
1417 	if (unlikely(!dentry))
1418 		goto need_lookup;
1419 
1420 	if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE) && need_reval)
1421 		status = d_revalidate(dentry, nd->flags);
1422 	if (unlikely(status <= 0)) {
1423 		if (status < 0) {
1424 			dput(dentry);
1425 			return status;
1426 		}
1427 		if (!d_invalidate(dentry)) {
1428 			dput(dentry);
1429 			goto need_lookup;
1430 		}
1431 	}
1432 
1433 	path->mnt = mnt;
1434 	path->dentry = dentry;
1435 	err = follow_managed(path, nd->flags);
1436 	if (unlikely(err < 0)) {
1437 		path_put_conditional(path, nd);
1438 		return err;
1439 	}
1440 	if (err)
1441 		nd->flags |= LOOKUP_JUMPED;
1442 	*inode = path->dentry->d_inode;
1443 	return 0;
1444 
1445 need_lookup:
1446 	return 1;
1447 }
1448 
1449 /* Fast lookup failed, do it the slow way */
lookup_slow(struct nameidata * nd,struct path * path)1450 static int lookup_slow(struct nameidata *nd, struct path *path)
1451 {
1452 	struct dentry *dentry, *parent;
1453 	int err;
1454 
1455 	parent = nd->path.dentry;
1456 	BUG_ON(nd->inode != parent->d_inode);
1457 
1458 	mutex_lock(&parent->d_inode->i_mutex);
1459 	dentry = __lookup_hash(&nd->last, parent, nd->flags);
1460 	mutex_unlock(&parent->d_inode->i_mutex);
1461 	if (IS_ERR(dentry))
1462 		return PTR_ERR(dentry);
1463 	path->mnt = nd->path.mnt;
1464 	path->dentry = dentry;
1465 	err = follow_managed(path, nd->flags);
1466 	if (unlikely(err < 0)) {
1467 		path_put_conditional(path, nd);
1468 		return err;
1469 	}
1470 	if (err)
1471 		nd->flags |= LOOKUP_JUMPED;
1472 	return 0;
1473 }
1474 
may_lookup(struct nameidata * nd)1475 static inline int may_lookup(struct nameidata *nd)
1476 {
1477 	if (nd->flags & LOOKUP_RCU) {
1478 		int err = inode_permission2(nd->path.mnt, nd->inode, MAY_EXEC|MAY_NOT_BLOCK);
1479 		if (err != -ECHILD)
1480 			return err;
1481 		if (unlazy_walk(nd, NULL))
1482 			return -ECHILD;
1483 	}
1484 	return inode_permission2(nd->path.mnt, nd->inode, MAY_EXEC);
1485 }
1486 
handle_dots(struct nameidata * nd,int type)1487 static inline int handle_dots(struct nameidata *nd, int type)
1488 {
1489 	if (type == LAST_DOTDOT) {
1490 		if (nd->flags & LOOKUP_RCU) {
1491 			if (follow_dotdot_rcu(nd))
1492 				return -ECHILD;
1493 		} else
1494 			follow_dotdot(nd);
1495 	}
1496 	return 0;
1497 }
1498 
terminate_walk(struct nameidata * nd)1499 static void terminate_walk(struct nameidata *nd)
1500 {
1501 	if (!(nd->flags & LOOKUP_RCU)) {
1502 		path_put(&nd->path);
1503 	} else {
1504 		nd->flags &= ~LOOKUP_RCU;
1505 		if (!(nd->flags & LOOKUP_ROOT))
1506 			nd->root.mnt = NULL;
1507 		unlock_rcu_walk();
1508 	}
1509 }
1510 
1511 /*
1512  * Do we need to follow links? We _really_ want to be able
1513  * to do this check without having to look at inode->i_op,
1514  * so we keep a cache of "no, this doesn't need follow_link"
1515  * for the common case.
1516  */
should_follow_link(struct inode * inode,int follow)1517 static inline int should_follow_link(struct inode *inode, int follow)
1518 {
1519 	if (unlikely(!(inode->i_opflags & IOP_NOFOLLOW))) {
1520 		if (likely(inode->i_op->follow_link))
1521 			return follow;
1522 
1523 		/* This gets set once for the inode lifetime */
1524 		spin_lock(&inode->i_lock);
1525 		inode->i_opflags |= IOP_NOFOLLOW;
1526 		spin_unlock(&inode->i_lock);
1527 	}
1528 	return 0;
1529 }
1530 
walk_component(struct nameidata * nd,struct path * path,int follow)1531 static inline int walk_component(struct nameidata *nd, struct path *path,
1532 		int follow)
1533 {
1534 	struct inode *inode;
1535 	int err;
1536 	/*
1537 	 * "." and ".." are special - ".." especially so because it has
1538 	 * to be able to know about the current root directory and
1539 	 * parent relationships.
1540 	 */
1541 	if (unlikely(nd->last_type != LAST_NORM))
1542 		return handle_dots(nd, nd->last_type);
1543 	err = lookup_fast(nd, path, &inode);
1544 	if (unlikely(err)) {
1545 		if (err < 0)
1546 			goto out_err;
1547 
1548 		err = lookup_slow(nd, path);
1549 		if (err < 0)
1550 			goto out_err;
1551 
1552 		inode = path->dentry->d_inode;
1553 	}
1554 	err = -ENOENT;
1555 	if (!inode)
1556 		goto out_path_put;
1557 
1558 	if (should_follow_link(inode, follow)) {
1559 		if (nd->flags & LOOKUP_RCU) {
1560 			if (unlikely(unlazy_walk(nd, path->dentry))) {
1561 				err = -ECHILD;
1562 				goto out_err;
1563 			}
1564 		}
1565 		BUG_ON(inode != path->dentry->d_inode);
1566 		return 1;
1567 	}
1568 	path_to_nameidata(path, nd);
1569 	nd->inode = inode;
1570 	return 0;
1571 
1572 out_path_put:
1573 	path_to_nameidata(path, nd);
1574 out_err:
1575 	terminate_walk(nd);
1576 	return err;
1577 }
1578 
1579 /*
1580  * This limits recursive symlink follows to 8, while
1581  * limiting consecutive symlinks to 40.
1582  *
1583  * Without that kind of total limit, nasty chains of consecutive
1584  * symlinks can cause almost arbitrarily long lookups.
1585  */
nested_symlink(struct path * path,struct nameidata * nd)1586 static inline int nested_symlink(struct path *path, struct nameidata *nd)
1587 {
1588 	int res;
1589 
1590 	if (unlikely(current->link_count >= MAX_NESTED_LINKS)) {
1591 		path_put_conditional(path, nd);
1592 		path_put(&nd->path);
1593 		return -ELOOP;
1594 	}
1595 	BUG_ON(nd->depth >= MAX_NESTED_LINKS);
1596 
1597 	nd->depth++;
1598 	current->link_count++;
1599 
1600 	do {
1601 		struct path link = *path;
1602 		void *cookie;
1603 
1604 		res = follow_link(&link, nd, &cookie);
1605 		if (res)
1606 			break;
1607 		res = walk_component(nd, path, LOOKUP_FOLLOW);
1608 		put_link(nd, &link, cookie);
1609 	} while (res > 0);
1610 
1611 	current->link_count--;
1612 	nd->depth--;
1613 	return res;
1614 }
1615 
1616 /*
1617  * We really don't want to look at inode->i_op->lookup
1618  * when we don't have to. So we keep a cache bit in
1619  * the inode ->i_opflags field that says "yes, we can
1620  * do lookup on this inode".
1621  */
can_lookup(struct inode * inode)1622 static inline int can_lookup(struct inode *inode)
1623 {
1624 	if (likely(inode->i_opflags & IOP_LOOKUP))
1625 		return 1;
1626 	if (likely(!inode->i_op->lookup))
1627 		return 0;
1628 
1629 	/* We do this once for the lifetime of the inode */
1630 	spin_lock(&inode->i_lock);
1631 	inode->i_opflags |= IOP_LOOKUP;
1632 	spin_unlock(&inode->i_lock);
1633 	return 1;
1634 }
1635 
1636 /*
1637  * We can do the critical dentry name comparison and hashing
1638  * operations one word at a time, but we are limited to:
1639  *
1640  * - Architectures with fast unaligned word accesses. We could
1641  *   do a "get_unaligned()" if this helps and is sufficiently
1642  *   fast.
1643  *
1644  * - Little-endian machines (so that we can generate the mask
1645  *   of low bytes efficiently). Again, we *could* do a byte
1646  *   swapping load on big-endian architectures if that is not
1647  *   expensive enough to make the optimization worthless.
1648  *
1649  * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we
1650  *   do not trap on the (extremely unlikely) case of a page
1651  *   crossing operation.
1652  *
1653  * - Furthermore, we need an efficient 64-bit compile for the
1654  *   64-bit case in order to generate the "number of bytes in
1655  *   the final mask". Again, that could be replaced with a
1656  *   efficient population count instruction or similar.
1657  */
1658 #ifdef CONFIG_DCACHE_WORD_ACCESS
1659 
1660 #include <asm/word-at-a-time.h>
1661 
1662 #ifdef CONFIG_64BIT
1663 
fold_hash(unsigned long hash)1664 static inline unsigned int fold_hash(unsigned long hash)
1665 {
1666 	hash += hash >> (8*sizeof(int));
1667 	return hash;
1668 }
1669 
1670 #else	/* 32-bit case */
1671 
1672 #define fold_hash(x) (x)
1673 
1674 #endif
1675 
full_name_hash(const unsigned char * name,unsigned int len)1676 unsigned int full_name_hash(const unsigned char *name, unsigned int len)
1677 {
1678 	unsigned long a, mask;
1679 	unsigned long hash = 0;
1680 
1681 	for (;;) {
1682 		a = load_unaligned_zeropad(name);
1683 		if (len < sizeof(unsigned long))
1684 			break;
1685 		hash += a;
1686 		hash *= 9;
1687 		name += sizeof(unsigned long);
1688 		len -= sizeof(unsigned long);
1689 		if (!len)
1690 			goto done;
1691 	}
1692 	mask = ~(~0ul << len*8);
1693 	hash += mask & a;
1694 done:
1695 	return fold_hash(hash);
1696 }
1697 EXPORT_SYMBOL(full_name_hash);
1698 
1699 /*
1700  * Calculate the length and hash of the path component, and
1701  * return the length of the component;
1702  */
hash_name(const char * name,unsigned int * hashp)1703 static inline unsigned long hash_name(const char *name, unsigned int *hashp)
1704 {
1705 	unsigned long a, b, adata, bdata, mask, hash, len;
1706 	const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
1707 
1708 	hash = a = 0;
1709 	len = -sizeof(unsigned long);
1710 	do {
1711 		hash = (hash + a) * 9;
1712 		len += sizeof(unsigned long);
1713 		a = load_unaligned_zeropad(name+len);
1714 		b = a ^ REPEAT_BYTE('/');
1715 	} while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)));
1716 
1717 	adata = prep_zero_mask(a, adata, &constants);
1718 	bdata = prep_zero_mask(b, bdata, &constants);
1719 
1720 	mask = create_zero_mask(adata | bdata);
1721 
1722 	hash += a & zero_bytemask(mask);
1723 	*hashp = fold_hash(hash);
1724 
1725 	return len + find_zero(mask);
1726 }
1727 
1728 #else
1729 
full_name_hash(const unsigned char * name,unsigned int len)1730 unsigned int full_name_hash(const unsigned char *name, unsigned int len)
1731 {
1732 	unsigned long hash = init_name_hash();
1733 	while (len--)
1734 		hash = partial_name_hash(*name++, hash);
1735 	return end_name_hash(hash);
1736 }
1737 EXPORT_SYMBOL(full_name_hash);
1738 
1739 /*
1740  * We know there's a real path component here of at least
1741  * one character.
1742  */
hash_name(const char * name,unsigned int * hashp)1743 static inline unsigned long hash_name(const char *name, unsigned int *hashp)
1744 {
1745 	unsigned long hash = init_name_hash();
1746 	unsigned long len = 0, c;
1747 
1748 	c = (unsigned char)*name;
1749 	do {
1750 		len++;
1751 		hash = partial_name_hash(c, hash);
1752 		c = (unsigned char)name[len];
1753 	} while (c && c != '/');
1754 	*hashp = end_name_hash(hash);
1755 	return len;
1756 }
1757 
1758 #endif
1759 
1760 /*
1761  * Name resolution.
1762  * This is the basic name resolution function, turning a pathname into
1763  * the final dentry. We expect 'base' to be positive and a directory.
1764  *
1765  * Returns 0 and nd will have valid dentry and mnt on success.
1766  * Returns error and drops reference to input namei data on failure.
1767  */
link_path_walk(const char * name,struct nameidata * nd)1768 static int link_path_walk(const char *name, struct nameidata *nd)
1769 {
1770 	struct path next;
1771 	int err;
1772 
1773 	while (*name=='/')
1774 		name++;
1775 	if (!*name)
1776 		return 0;
1777 
1778 	/* At this point we know we have a real path component. */
1779 	for(;;) {
1780 		struct qstr this;
1781 		long len;
1782 		int type;
1783 
1784 		err = may_lookup(nd);
1785  		if (err)
1786 			break;
1787 
1788 		len = hash_name(name, &this.hash);
1789 		this.name = name;
1790 		this.len = len;
1791 
1792 		type = LAST_NORM;
1793 		if (name[0] == '.') switch (len) {
1794 			case 2:
1795 				if (name[1] == '.') {
1796 					type = LAST_DOTDOT;
1797 					nd->flags |= LOOKUP_JUMPED;
1798 				}
1799 				break;
1800 			case 1:
1801 				type = LAST_DOT;
1802 		}
1803 		if (likely(type == LAST_NORM)) {
1804 			struct dentry *parent = nd->path.dentry;
1805 			nd->flags &= ~LOOKUP_JUMPED;
1806 			if (unlikely(parent->d_flags & DCACHE_OP_HASH)) {
1807 				err = parent->d_op->d_hash(parent, nd->inode,
1808 							   &this);
1809 				if (err < 0)
1810 					break;
1811 			}
1812 		}
1813 
1814 		nd->last = this;
1815 		nd->last_type = type;
1816 
1817 		if (!name[len])
1818 			return 0;
1819 		/*
1820 		 * If it wasn't NUL, we know it was '/'. Skip that
1821 		 * slash, and continue until no more slashes.
1822 		 */
1823 		do {
1824 			len++;
1825 		} while (unlikely(name[len] == '/'));
1826 		if (!name[len])
1827 			return 0;
1828 
1829 		name += len;
1830 
1831 		err = walk_component(nd, &next, LOOKUP_FOLLOW);
1832 		if (err < 0)
1833 			return err;
1834 
1835 		if (err) {
1836 			err = nested_symlink(&next, nd);
1837 			if (err)
1838 				return err;
1839 		}
1840 		if (!can_lookup(nd->inode)) {
1841 			err = -ENOTDIR;
1842 			break;
1843 		}
1844 	}
1845 	terminate_walk(nd);
1846 	return err;
1847 }
1848 
path_init(int dfd,const char * name,unsigned int flags,struct nameidata * nd,struct file ** fp)1849 static int path_init(int dfd, const char *name, unsigned int flags,
1850 		     struct nameidata *nd, struct file **fp)
1851 {
1852 	int retval = 0;
1853 
1854 	nd->last_type = LAST_ROOT; /* if there are only slashes... */
1855 	nd->flags = flags | LOOKUP_JUMPED;
1856 	nd->depth = 0;
1857 	if (flags & LOOKUP_ROOT) {
1858 		struct inode *inode = nd->root.dentry->d_inode;
1859 		struct vfsmount *mnt = nd->root.mnt;
1860 		if (*name) {
1861 			if (!can_lookup(inode))
1862 				return -ENOTDIR;
1863 			retval = inode_permission2(mnt, inode, MAY_EXEC);
1864 			if (retval)
1865 				return retval;
1866 		}
1867 		nd->path = nd->root;
1868 		nd->inode = inode;
1869 		if (flags & LOOKUP_RCU) {
1870 			lock_rcu_walk();
1871 			nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
1872 		} else {
1873 			path_get(&nd->path);
1874 		}
1875 		return 0;
1876 	}
1877 
1878 	nd->root.mnt = NULL;
1879 
1880 	if (*name=='/') {
1881 		if (flags & LOOKUP_RCU) {
1882 			lock_rcu_walk();
1883 			set_root_rcu(nd);
1884 		} else {
1885 			set_root(nd);
1886 			path_get(&nd->root);
1887 		}
1888 		nd->path = nd->root;
1889 	} else if (dfd == AT_FDCWD) {
1890 		if (flags & LOOKUP_RCU) {
1891 			struct fs_struct *fs = current->fs;
1892 			unsigned seq;
1893 
1894 			lock_rcu_walk();
1895 
1896 			do {
1897 				seq = read_seqcount_begin(&fs->seq);
1898 				nd->path = fs->pwd;
1899 				nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
1900 			} while (read_seqcount_retry(&fs->seq, seq));
1901 		} else {
1902 			get_fs_pwd(current->fs, &nd->path);
1903 		}
1904 	} else {
1905 		/* Caller must check execute permissions on the starting path component */
1906 		struct fd f = fdget_raw(dfd);
1907 		struct dentry *dentry;
1908 
1909 		if (!f.file)
1910 			return -EBADF;
1911 
1912 		dentry = f.file->f_path.dentry;
1913 
1914 		if (*name) {
1915 			if (!can_lookup(dentry->d_inode)) {
1916 				fdput(f);
1917 				return -ENOTDIR;
1918 			}
1919 		}
1920 
1921 		nd->path = f.file->f_path;
1922 		if (flags & LOOKUP_RCU) {
1923 			if (f.need_put)
1924 				*fp = f.file;
1925 			nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
1926 			lock_rcu_walk();
1927 		} else {
1928 			path_get(&nd->path);
1929 			fdput(f);
1930 		}
1931 	}
1932 
1933 	nd->inode = nd->path.dentry->d_inode;
1934 	return 0;
1935 }
1936 
lookup_last(struct nameidata * nd,struct path * path)1937 static inline int lookup_last(struct nameidata *nd, struct path *path)
1938 {
1939 	if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len])
1940 		nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
1941 
1942 	nd->flags &= ~LOOKUP_PARENT;
1943 	return walk_component(nd, path, nd->flags & LOOKUP_FOLLOW);
1944 }
1945 
1946 /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
path_lookupat(int dfd,const char * name,unsigned int flags,struct nameidata * nd)1947 static int path_lookupat(int dfd, const char *name,
1948 				unsigned int flags, struct nameidata *nd)
1949 {
1950 	struct file *base = NULL;
1951 	struct path path;
1952 	int err;
1953 
1954 	/*
1955 	 * Path walking is largely split up into 2 different synchronisation
1956 	 * schemes, rcu-walk and ref-walk (explained in
1957 	 * Documentation/filesystems/path-lookup.txt). These share much of the
1958 	 * path walk code, but some things particularly setup, cleanup, and
1959 	 * following mounts are sufficiently divergent that functions are
1960 	 * duplicated. Typically there is a function foo(), and its RCU
1961 	 * analogue, foo_rcu().
1962 	 *
1963 	 * -ECHILD is the error number of choice (just to avoid clashes) that
1964 	 * is returned if some aspect of an rcu-walk fails. Such an error must
1965 	 * be handled by restarting a traditional ref-walk (which will always
1966 	 * be able to complete).
1967 	 */
1968 	err = path_init(dfd, name, flags | LOOKUP_PARENT, nd, &base);
1969 
1970 	if (unlikely(err))
1971 		return err;
1972 
1973 	current->total_link_count = 0;
1974 	err = link_path_walk(name, nd);
1975 
1976 	if (!err && !(flags & LOOKUP_PARENT)) {
1977 		err = lookup_last(nd, &path);
1978 		while (err > 0) {
1979 			void *cookie;
1980 			struct path link = path;
1981 			err = may_follow_link(&link, nd);
1982 			if (unlikely(err))
1983 				break;
1984 			nd->flags |= LOOKUP_PARENT;
1985 			err = follow_link(&link, nd, &cookie);
1986 			if (err)
1987 				break;
1988 			err = lookup_last(nd, &path);
1989 			put_link(nd, &link, cookie);
1990 		}
1991 	}
1992 
1993 	if (!err)
1994 		err = complete_walk(nd);
1995 
1996 	if (!err && nd->flags & LOOKUP_DIRECTORY) {
1997 		if (!can_lookup(nd->inode)) {
1998 			path_put(&nd->path);
1999 			err = -ENOTDIR;
2000 		}
2001 	}
2002 
2003 	if (base)
2004 		fput(base);
2005 
2006 	if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT)) {
2007 		path_put(&nd->root);
2008 		nd->root.mnt = NULL;
2009 	}
2010 	return err;
2011 }
2012 
filename_lookup(int dfd,struct filename * name,unsigned int flags,struct nameidata * nd)2013 static int filename_lookup(int dfd, struct filename *name,
2014 				unsigned int flags, struct nameidata *nd)
2015 {
2016 	int retval = path_lookupat(dfd, name->name, flags | LOOKUP_RCU, nd);
2017 	if (unlikely(retval == -ECHILD))
2018 		retval = path_lookupat(dfd, name->name, flags, nd);
2019 	if (unlikely(retval == -ESTALE))
2020 		retval = path_lookupat(dfd, name->name,
2021 						flags | LOOKUP_REVAL, nd);
2022 
2023 	if (likely(!retval))
2024 		audit_inode(name, nd->path.dentry, flags & LOOKUP_PARENT);
2025 	return retval;
2026 }
2027 
do_path_lookup(int dfd,const char * name,unsigned int flags,struct nameidata * nd)2028 static int do_path_lookup(int dfd, const char *name,
2029 				unsigned int flags, struct nameidata *nd)
2030 {
2031 	struct filename filename = { .name = name };
2032 
2033 	return filename_lookup(dfd, &filename, flags, nd);
2034 }
2035 
2036 /* does lookup, returns the object with parent locked */
kern_path_locked(const char * name,struct path * path)2037 struct dentry *kern_path_locked(const char *name, struct path *path)
2038 {
2039 	struct nameidata nd;
2040 	struct dentry *d;
2041 	int err = do_path_lookup(AT_FDCWD, name, LOOKUP_PARENT, &nd);
2042 	if (err)
2043 		return ERR_PTR(err);
2044 	if (nd.last_type != LAST_NORM) {
2045 		path_put(&nd.path);
2046 		return ERR_PTR(-EINVAL);
2047 	}
2048 	mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
2049 	d = __lookup_hash(&nd.last, nd.path.dentry, 0);
2050 	if (IS_ERR(d)) {
2051 		mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
2052 		path_put(&nd.path);
2053 		return d;
2054 	}
2055 	*path = nd.path;
2056 	return d;
2057 }
2058 
kern_path(const char * name,unsigned int flags,struct path * path)2059 int kern_path(const char *name, unsigned int flags, struct path *path)
2060 {
2061 	struct nameidata nd;
2062 	int res = do_path_lookup(AT_FDCWD, name, flags, &nd);
2063 	if (!res)
2064 		*path = nd.path;
2065 	return res;
2066 }
2067 
2068 /**
2069  * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
2070  * @dentry:  pointer to dentry of the base directory
2071  * @mnt: pointer to vfs mount of the base directory
2072  * @name: pointer to file name
2073  * @flags: lookup flags
2074  * @path: pointer to struct path to fill
2075  */
vfs_path_lookup(struct dentry * dentry,struct vfsmount * mnt,const char * name,unsigned int flags,struct path * path)2076 int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
2077 		    const char *name, unsigned int flags,
2078 		    struct path *path)
2079 {
2080 	struct nameidata nd;
2081 	int err;
2082 	nd.root.dentry = dentry;
2083 	nd.root.mnt = mnt;
2084 	BUG_ON(flags & LOOKUP_PARENT);
2085 	/* the first argument of do_path_lookup() is ignored with LOOKUP_ROOT */
2086 	err = do_path_lookup(AT_FDCWD, name, flags | LOOKUP_ROOT, &nd);
2087 	if (!err)
2088 		*path = nd.path;
2089 	return err;
2090 }
2091 
2092 /*
2093  * Restricted form of lookup. Doesn't follow links, single-component only,
2094  * needs parent already locked. Doesn't follow mounts.
2095  * SMP-safe.
2096  */
lookup_hash(struct nameidata * nd)2097 static struct dentry *lookup_hash(struct nameidata *nd)
2098 {
2099 	return __lookup_hash(&nd->last, nd->path.dentry, nd->flags);
2100 }
2101 
2102 /**
2103  * lookup_one_len - filesystem helper to lookup single pathname component
2104  * @name:	pathname component to lookup
2105  * @mnt:	mount we are looking up on
2106  * @base:	base directory to lookup from
2107  * @len:	maximum length @len should be interpreted to
2108  *
2109  * Note that this routine is purely a helper for filesystem usage and should
2110  * not be called by generic code.  Also note that by using this function the
2111  * nameidata argument is passed to the filesystem methods and a filesystem
2112  * using this helper needs to be prepared for that.
2113  */
lookup_one_len2(const char * name,struct vfsmount * mnt,struct dentry * base,int len)2114 struct dentry *lookup_one_len2(const char *name, struct vfsmount *mnt, struct dentry *base, int len)
2115 {
2116 	struct qstr this;
2117 	unsigned int c;
2118 	int err;
2119 
2120 	WARN_ON_ONCE(!mutex_is_locked(&base->d_inode->i_mutex));
2121 
2122 	this.name = name;
2123 	this.len = len;
2124 	this.hash = full_name_hash(name, len);
2125 	if (!len)
2126 		return ERR_PTR(-EACCES);
2127 
2128 	if (unlikely(name[0] == '.')) {
2129 		if (len < 2 || (len == 2 && name[1] == '.'))
2130 			return ERR_PTR(-EACCES);
2131 	}
2132 
2133 	while (len--) {
2134 		c = *(const unsigned char *)name++;
2135 		if (c == '/' || c == '\0')
2136 			return ERR_PTR(-EACCES);
2137 	}
2138 	/*
2139 	 * See if the low-level filesystem might want
2140 	 * to use its own hash..
2141 	 */
2142 	if (base->d_flags & DCACHE_OP_HASH) {
2143 		int err = base->d_op->d_hash(base, base->d_inode, &this);
2144 		if (err < 0)
2145 			return ERR_PTR(err);
2146 	}
2147 
2148 	err = inode_permission2(mnt, base->d_inode, MAY_EXEC);
2149 	if (err)
2150 		return ERR_PTR(err);
2151 
2152 	return __lookup_hash(&this, base, 0);
2153 }
2154 EXPORT_SYMBOL(lookup_one_len2);
2155 
lookup_one_len(const char * name,struct dentry * base,int len)2156 struct dentry *lookup_one_len(const char *name, struct dentry *base, int len)
2157 {
2158 	return lookup_one_len2(name, NULL, base, len);
2159 }
2160 EXPORT_SYMBOL(lookup_one_len);
2161 
user_path_at_empty(int dfd,const char __user * name,unsigned flags,struct path * path,int * empty)2162 int user_path_at_empty(int dfd, const char __user *name, unsigned flags,
2163 		 struct path *path, int *empty)
2164 {
2165 	struct nameidata nd;
2166 	struct filename *tmp = getname_flags(name, flags, empty);
2167 	int err = PTR_ERR(tmp);
2168 	if (!IS_ERR(tmp)) {
2169 
2170 		BUG_ON(flags & LOOKUP_PARENT);
2171 
2172 		err = filename_lookup(dfd, tmp, flags, &nd);
2173 		putname(tmp);
2174 		if (!err)
2175 			*path = nd.path;
2176 	}
2177 	return err;
2178 }
2179 
user_path_at(int dfd,const char __user * name,unsigned flags,struct path * path)2180 int user_path_at(int dfd, const char __user *name, unsigned flags,
2181 		 struct path *path)
2182 {
2183 	return user_path_at_empty(dfd, name, flags, path, NULL);
2184 }
2185 
2186 /*
2187  * NB: most callers don't do anything directly with the reference to the
2188  *     to struct filename, but the nd->last pointer points into the name string
2189  *     allocated by getname. So we must hold the reference to it until all
2190  *     path-walking is complete.
2191  */
2192 static struct filename *
user_path_parent(int dfd,const char __user * path,struct nameidata * nd,unsigned int flags)2193 user_path_parent(int dfd, const char __user *path, struct nameidata *nd,
2194 		 unsigned int flags)
2195 {
2196 	struct filename *s = getname(path);
2197 	int error;
2198 
2199 	/* only LOOKUP_REVAL is allowed in extra flags */
2200 	flags &= LOOKUP_REVAL;
2201 
2202 	if (IS_ERR(s))
2203 		return s;
2204 
2205 	error = filename_lookup(dfd, s, flags | LOOKUP_PARENT, nd);
2206 	if (error) {
2207 		putname(s);
2208 		return ERR_PTR(error);
2209 	}
2210 
2211 	return s;
2212 }
2213 
2214 /*
2215  * It's inline, so penalty for filesystems that don't use sticky bit is
2216  * minimal.
2217  */
check_sticky(struct inode * dir,struct inode * inode)2218 static inline int check_sticky(struct inode *dir, struct inode *inode)
2219 {
2220 	kuid_t fsuid = current_fsuid();
2221 
2222 	if (!(dir->i_mode & S_ISVTX))
2223 		return 0;
2224 	if (uid_eq(inode->i_uid, fsuid))
2225 		return 0;
2226 	if (uid_eq(dir->i_uid, fsuid))
2227 		return 0;
2228 	return !capable_wrt_inode_uidgid(inode, CAP_FOWNER);
2229 }
2230 
2231 /*
2232  *	Check whether we can remove a link victim from directory dir, check
2233  *  whether the type of victim is right.
2234  *  1. We can't do it if dir is read-only (done in permission())
2235  *  2. We should have write and exec permissions on dir
2236  *  3. We can't remove anything from append-only dir
2237  *  4. We can't do anything with immutable dir (done in permission())
2238  *  5. If the sticky bit on dir is set we should either
2239  *	a. be owner of dir, or
2240  *	b. be owner of victim, or
2241  *	c. have CAP_FOWNER capability
2242  *  6. If the victim is append-only or immutable we can't do antyhing with
2243  *     links pointing to it.
2244  *  7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
2245  *  8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
2246  *  9. We can't remove a root or mountpoint.
2247  * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
2248  *     nfs_async_unlink().
2249  */
may_delete(struct vfsmount * mnt,struct inode * dir,struct dentry * victim,int isdir)2250 static int may_delete(struct vfsmount *mnt, struct inode *dir,struct dentry *victim,int isdir)
2251 {
2252 	int error;
2253 
2254 	if (!victim->d_inode)
2255 		return -ENOENT;
2256 
2257 	BUG_ON(victim->d_parent->d_inode != dir);
2258 	audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
2259 
2260 	error = inode_permission2(mnt, dir, MAY_WRITE | MAY_EXEC);
2261 	if (error)
2262 		return error;
2263 	if (IS_APPEND(dir))
2264 		return -EPERM;
2265 	if (check_sticky(dir, victim->d_inode)||IS_APPEND(victim->d_inode)||
2266 	    IS_IMMUTABLE(victim->d_inode) || IS_SWAPFILE(victim->d_inode))
2267 		return -EPERM;
2268 	if (isdir) {
2269 		if (!S_ISDIR(victim->d_inode->i_mode))
2270 			return -ENOTDIR;
2271 		if (IS_ROOT(victim))
2272 			return -EBUSY;
2273 	} else if (S_ISDIR(victim->d_inode->i_mode))
2274 		return -EISDIR;
2275 	if (IS_DEADDIR(dir))
2276 		return -ENOENT;
2277 	if (victim->d_flags & DCACHE_NFSFS_RENAMED)
2278 		return -EBUSY;
2279 	return 0;
2280 }
2281 
2282 /*	Check whether we can create an object with dentry child in directory
2283  *  dir.
2284  *  1. We can't do it if child already exists (open has special treatment for
2285  *     this case, but since we are inlined it's OK)
2286  *  2. We can't do it if dir is read-only (done in permission())
2287  *  3. We should have write and exec permissions on dir
2288  *  4. We can't do it if dir is immutable (done in permission())
2289  */
may_create(struct vfsmount * mnt,struct inode * dir,struct dentry * child)2290 static inline int may_create(struct vfsmount *mnt, struct inode *dir, struct dentry *child)
2291 {
2292 	if (child->d_inode)
2293 		return -EEXIST;
2294 	if (IS_DEADDIR(dir))
2295 		return -ENOENT;
2296 	return inode_permission2(mnt, dir, MAY_WRITE | MAY_EXEC);
2297 }
2298 
2299 /*
2300  * p1 and p2 should be directories on the same fs.
2301  */
lock_rename(struct dentry * p1,struct dentry * p2)2302 struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
2303 {
2304 	struct dentry *p;
2305 
2306 	if (p1 == p2) {
2307 		mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT);
2308 		return NULL;
2309 	}
2310 
2311 	mutex_lock(&p1->d_inode->i_sb->s_vfs_rename_mutex);
2312 
2313 	p = d_ancestor(p2, p1);
2314 	if (p) {
2315 		mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_PARENT);
2316 		mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_CHILD);
2317 		return p;
2318 	}
2319 
2320 	p = d_ancestor(p1, p2);
2321 	if (p) {
2322 		mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT);
2323 		mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_CHILD);
2324 		return p;
2325 	}
2326 
2327 	mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT);
2328 	mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_CHILD);
2329 	return NULL;
2330 }
2331 
unlock_rename(struct dentry * p1,struct dentry * p2)2332 void unlock_rename(struct dentry *p1, struct dentry *p2)
2333 {
2334 	mutex_unlock(&p1->d_inode->i_mutex);
2335 	if (p1 != p2) {
2336 		mutex_unlock(&p2->d_inode->i_mutex);
2337 		mutex_unlock(&p1->d_inode->i_sb->s_vfs_rename_mutex);
2338 	}
2339 }
2340 
vfs_create2(struct vfsmount * mnt,struct inode * dir,struct dentry * dentry,umode_t mode,bool want_excl)2341 int vfs_create2(struct vfsmount *mnt, struct inode *dir, struct dentry *dentry,
2342 		umode_t mode, bool want_excl)
2343 {
2344 	int error = may_create(mnt, dir, dentry);
2345 	if (error)
2346 		return error;
2347 
2348 	if (!dir->i_op->create)
2349 		return -EACCES;	/* shouldn't it be ENOSYS? */
2350 	mode &= S_IALLUGO;
2351 	mode |= S_IFREG;
2352 	error = security_inode_create(dir, dentry, mode);
2353 	if (error)
2354 		return error;
2355 	error = dir->i_op->create(dir, dentry, mode, want_excl);
2356 	if (!error)
2357 		fsnotify_create(dir, dentry);
2358 	return error;
2359 }
2360 EXPORT_SYMBOL(vfs_create2);
2361 
vfs_create(struct inode * dir,struct dentry * dentry,umode_t mode,bool want_excl)2362 int vfs_create(struct inode *dir, struct dentry *dentry, umode_t mode,
2363 		bool want_excl)
2364 {
2365 	return vfs_create2(NULL, dir, dentry, mode, want_excl);
2366 }
2367 EXPORT_SYMBOL(vfs_create);
2368 
may_open(struct path * path,int acc_mode,int flag)2369 static int may_open(struct path *path, int acc_mode, int flag)
2370 {
2371 	struct dentry *dentry = path->dentry;
2372 	struct vfsmount *mnt = path->mnt;
2373 	struct inode *inode = dentry->d_inode;
2374 	int error;
2375 
2376 	/* O_PATH? */
2377 	if (!acc_mode)
2378 		return 0;
2379 
2380 	if (!inode)
2381 		return -ENOENT;
2382 
2383 	switch (inode->i_mode & S_IFMT) {
2384 	case S_IFLNK:
2385 		return -ELOOP;
2386 	case S_IFDIR:
2387 		if (acc_mode & MAY_WRITE)
2388 			return -EISDIR;
2389 		break;
2390 	case S_IFBLK:
2391 	case S_IFCHR:
2392 		if (path->mnt->mnt_flags & MNT_NODEV)
2393 			return -EACCES;
2394 		/*FALLTHRU*/
2395 	case S_IFIFO:
2396 	case S_IFSOCK:
2397 		flag &= ~O_TRUNC;
2398 		break;
2399 	}
2400 
2401 	error = inode_permission2(mnt, inode, acc_mode);
2402 	if (error)
2403 		return error;
2404 
2405 	/*
2406 	 * An append-only file must be opened in append mode for writing.
2407 	 */
2408 	if (IS_APPEND(inode)) {
2409 		if  ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
2410 			return -EPERM;
2411 		if (flag & O_TRUNC)
2412 			return -EPERM;
2413 	}
2414 
2415 	/* O_NOATIME can only be set by the owner or superuser */
2416 	if (flag & O_NOATIME && !inode_owner_or_capable(inode))
2417 		return -EPERM;
2418 
2419 	return 0;
2420 }
2421 
handle_truncate(struct file * filp)2422 static int handle_truncate(struct file *filp)
2423 {
2424 	struct path *path = &filp->f_path;
2425 	struct inode *inode = path->dentry->d_inode;
2426 	int error = get_write_access(inode);
2427 	if (error)
2428 		return error;
2429 	/*
2430 	 * Refuse to truncate files with mandatory locks held on them.
2431 	 */
2432 	error = locks_verify_locked(inode);
2433 	if (!error)
2434 		error = security_path_truncate(path);
2435 	if (!error) {
2436 		error = do_truncate2(path->mnt, path->dentry, 0,
2437 				    ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
2438 				    filp);
2439 	}
2440 	put_write_access(inode);
2441 	return error;
2442 }
2443 
open_to_namei_flags(int flag)2444 static inline int open_to_namei_flags(int flag)
2445 {
2446 	if ((flag & O_ACCMODE) == 3)
2447 		flag--;
2448 	return flag;
2449 }
2450 
may_o_create(struct path * dir,struct dentry * dentry,umode_t mode)2451 static int may_o_create(struct path *dir, struct dentry *dentry, umode_t mode)
2452 {
2453 	int error = security_path_mknod(dir, dentry, mode, 0);
2454 	if (error)
2455 		return error;
2456 
2457 	error = inode_permission2(dir->mnt, dir->dentry->d_inode, MAY_WRITE | MAY_EXEC);
2458 	if (error)
2459 		return error;
2460 
2461 	return security_inode_create(dir->dentry->d_inode, dentry, mode);
2462 }
2463 
2464 /*
2465  * Attempt to atomically look up, create and open a file from a negative
2466  * dentry.
2467  *
2468  * Returns 0 if successful.  The file will have been created and attached to
2469  * @file by the filesystem calling finish_open().
2470  *
2471  * Returns 1 if the file was looked up only or didn't need creating.  The
2472  * caller will need to perform the open themselves.  @path will have been
2473  * updated to point to the new dentry.  This may be negative.
2474  *
2475  * Returns an error code otherwise.
2476  */
atomic_open(struct nameidata * nd,struct dentry * dentry,struct path * path,struct file * file,const struct open_flags * op,bool got_write,bool need_lookup,int * opened)2477 static int atomic_open(struct nameidata *nd, struct dentry *dentry,
2478 			struct path *path, struct file *file,
2479 			const struct open_flags *op,
2480 			bool got_write, bool need_lookup,
2481 			int *opened)
2482 {
2483 	struct inode *dir =  nd->path.dentry->d_inode;
2484 	unsigned open_flag = open_to_namei_flags(op->open_flag);
2485 	umode_t mode;
2486 	int error;
2487 	int acc_mode;
2488 	int create_error = 0;
2489 	struct dentry *const DENTRY_NOT_SET = (void *) -1UL;
2490 
2491 	BUG_ON(dentry->d_inode);
2492 
2493 	/* Don't create child dentry for a dead directory. */
2494 	if (unlikely(IS_DEADDIR(dir))) {
2495 		error = -ENOENT;
2496 		goto out;
2497 	}
2498 
2499 	mode = op->mode;
2500 	if ((open_flag & O_CREAT) && !IS_POSIXACL(dir))
2501 		mode &= ~current_umask();
2502 
2503 	if ((open_flag & (O_EXCL | O_CREAT)) == (O_EXCL | O_CREAT)) {
2504 		open_flag &= ~O_TRUNC;
2505 		*opened |= FILE_CREATED;
2506 	}
2507 
2508 	/*
2509 	 * Checking write permission is tricky, bacuse we don't know if we are
2510 	 * going to actually need it: O_CREAT opens should work as long as the
2511 	 * file exists.  But checking existence breaks atomicity.  The trick is
2512 	 * to check access and if not granted clear O_CREAT from the flags.
2513 	 *
2514 	 * Another problem is returing the "right" error value (e.g. for an
2515 	 * O_EXCL open we want to return EEXIST not EROFS).
2516 	 */
2517 	if (((open_flag & (O_CREAT | O_TRUNC)) ||
2518 	    (open_flag & O_ACCMODE) != O_RDONLY) && unlikely(!got_write)) {
2519 		if (!(open_flag & O_CREAT)) {
2520 			/*
2521 			 * No O_CREATE -> atomicity not a requirement -> fall
2522 			 * back to lookup + open
2523 			 */
2524 			goto no_open;
2525 		} else if (open_flag & (O_EXCL | O_TRUNC)) {
2526 			/* Fall back and fail with the right error */
2527 			create_error = -EROFS;
2528 			goto no_open;
2529 		} else {
2530 			/* No side effects, safe to clear O_CREAT */
2531 			create_error = -EROFS;
2532 			open_flag &= ~O_CREAT;
2533 		}
2534 	}
2535 
2536 	if (open_flag & O_CREAT) {
2537 		error = may_o_create(&nd->path, dentry, mode);
2538 		if (error) {
2539 			create_error = error;
2540 			if (open_flag & O_EXCL)
2541 				goto no_open;
2542 			open_flag &= ~O_CREAT;
2543 		}
2544 	}
2545 
2546 	if (nd->flags & LOOKUP_DIRECTORY)
2547 		open_flag |= O_DIRECTORY;
2548 
2549 	file->f_path.dentry = DENTRY_NOT_SET;
2550 	file->f_path.mnt = nd->path.mnt;
2551 	error = dir->i_op->atomic_open(dir, dentry, file, open_flag, mode,
2552 				      opened);
2553 	if (error < 0) {
2554 		if (create_error && error == -ENOENT)
2555 			error = create_error;
2556 		goto out;
2557 	}
2558 
2559 	acc_mode = op->acc_mode;
2560 	if (*opened & FILE_CREATED) {
2561 		fsnotify_create(dir, dentry);
2562 		acc_mode = MAY_OPEN;
2563 	}
2564 
2565 	if (error) {	/* returned 1, that is */
2566 		if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) {
2567 			error = -EIO;
2568 			goto out;
2569 		}
2570 		if (file->f_path.dentry) {
2571 			dput(dentry);
2572 			dentry = file->f_path.dentry;
2573 		}
2574 		if (create_error && dentry->d_inode == NULL) {
2575 			error = create_error;
2576 			goto out;
2577 		}
2578 		goto looked_up;
2579 	}
2580 
2581 	/*
2582 	 * We didn't have the inode before the open, so check open permission
2583 	 * here.
2584 	 */
2585 	error = may_open(&file->f_path, acc_mode, open_flag);
2586 	if (error)
2587 		fput(file);
2588 
2589 out:
2590 	dput(dentry);
2591 	return error;
2592 
2593 no_open:
2594 	if (need_lookup) {
2595 		dentry = lookup_real(dir, dentry, nd->flags);
2596 		if (IS_ERR(dentry))
2597 			return PTR_ERR(dentry);
2598 
2599 		if (create_error) {
2600 			int open_flag = op->open_flag;
2601 
2602 			error = create_error;
2603 			if ((open_flag & O_EXCL)) {
2604 				if (!dentry->d_inode)
2605 					goto out;
2606 			} else if (!dentry->d_inode) {
2607 				goto out;
2608 			} else if ((open_flag & O_TRUNC) &&
2609 				   S_ISREG(dentry->d_inode->i_mode)) {
2610 				goto out;
2611 			}
2612 			/* will fail later, go on to get the right error */
2613 		}
2614 	}
2615 looked_up:
2616 	path->dentry = dentry;
2617 	path->mnt = nd->path.mnt;
2618 	return 1;
2619 }
2620 
2621 /*
2622  * Look up and maybe create and open the last component.
2623  *
2624  * Must be called with i_mutex held on parent.
2625  *
2626  * Returns 0 if the file was successfully atomically created (if necessary) and
2627  * opened.  In this case the file will be returned attached to @file.
2628  *
2629  * Returns 1 if the file was not completely opened at this time, though lookups
2630  * and creations will have been performed and the dentry returned in @path will
2631  * be positive upon return if O_CREAT was specified.  If O_CREAT wasn't
2632  * specified then a negative dentry may be returned.
2633  *
2634  * An error code is returned otherwise.
2635  *
2636  * FILE_CREATE will be set in @*opened if the dentry was created and will be
2637  * cleared otherwise prior to returning.
2638  */
lookup_open(struct nameidata * nd,struct path * path,struct file * file,const struct open_flags * op,bool got_write,int * opened)2639 static int lookup_open(struct nameidata *nd, struct path *path,
2640 			struct file *file,
2641 			const struct open_flags *op,
2642 			bool got_write, int *opened)
2643 {
2644 	struct dentry *dir = nd->path.dentry;
2645 	struct vfsmount *mnt = nd->path.mnt;
2646 	struct inode *dir_inode = dir->d_inode;
2647 	struct dentry *dentry;
2648 	int error;
2649 	bool need_lookup;
2650 
2651 	*opened &= ~FILE_CREATED;
2652 	dentry = lookup_dcache(&nd->last, dir, nd->flags, &need_lookup);
2653 	if (IS_ERR(dentry))
2654 		return PTR_ERR(dentry);
2655 
2656 	/* Cached positive dentry: will open in f_op->open */
2657 	if (!need_lookup && dentry->d_inode)
2658 		goto out_no_open;
2659 
2660 	if ((nd->flags & LOOKUP_OPEN) && dir_inode->i_op->atomic_open) {
2661 		return atomic_open(nd, dentry, path, file, op, got_write,
2662 				   need_lookup, opened);
2663 	}
2664 
2665 	if (need_lookup) {
2666 		BUG_ON(dentry->d_inode);
2667 
2668 		dentry = lookup_real(dir_inode, dentry, nd->flags);
2669 		if (IS_ERR(dentry))
2670 			return PTR_ERR(dentry);
2671 	}
2672 
2673 	/* Negative dentry, just create the file */
2674 	if (!dentry->d_inode && (op->open_flag & O_CREAT)) {
2675 		umode_t mode = op->mode;
2676 		if (!IS_POSIXACL(dir->d_inode))
2677 			mode &= ~current_umask();
2678 		/*
2679 		 * This write is needed to ensure that a
2680 		 * rw->ro transition does not occur between
2681 		 * the time when the file is created and when
2682 		 * a permanent write count is taken through
2683 		 * the 'struct file' in finish_open().
2684 		 */
2685 		if (!got_write) {
2686 			error = -EROFS;
2687 			goto out_dput;
2688 		}
2689 		*opened |= FILE_CREATED;
2690 		error = security_path_mknod(&nd->path, dentry, mode, 0);
2691 		if (error)
2692 			goto out_dput;
2693 		error = vfs_create2(mnt, dir->d_inode, dentry, mode,
2694 				   nd->flags & LOOKUP_EXCL);
2695 		if (error)
2696 			goto out_dput;
2697 	}
2698 out_no_open:
2699 	path->dentry = dentry;
2700 	path->mnt = nd->path.mnt;
2701 	return 1;
2702 
2703 out_dput:
2704 	dput(dentry);
2705 	return error;
2706 }
2707 
2708 /*
2709  * Handle the last step of open()
2710  */
do_last(struct nameidata * nd,struct path * path,struct file * file,const struct open_flags * op,int * opened,struct filename * name)2711 static int do_last(struct nameidata *nd, struct path *path,
2712 		   struct file *file, const struct open_flags *op,
2713 		   int *opened, struct filename *name)
2714 {
2715 	struct dentry *dir = nd->path.dentry;
2716 	int open_flag = op->open_flag;
2717 	bool will_truncate = (open_flag & O_TRUNC) != 0;
2718 	bool got_write = false;
2719 	int acc_mode = op->acc_mode;
2720 	struct inode *inode;
2721 	bool symlink_ok = false;
2722 	struct path save_parent = { .dentry = NULL, .mnt = NULL };
2723 	bool retried = false;
2724 	int error;
2725 
2726 	nd->flags &= ~LOOKUP_PARENT;
2727 	nd->flags |= op->intent;
2728 
2729 	switch (nd->last_type) {
2730 	case LAST_DOTDOT:
2731 	case LAST_DOT:
2732 		error = handle_dots(nd, nd->last_type);
2733 		if (error)
2734 			return error;
2735 		/* fallthrough */
2736 	case LAST_ROOT:
2737 		error = complete_walk(nd);
2738 		if (error)
2739 			return error;
2740 		audit_inode(name, nd->path.dentry, 0);
2741 		if (open_flag & O_CREAT) {
2742 			error = -EISDIR;
2743 			goto out;
2744 		}
2745 		goto finish_open;
2746 	case LAST_BIND:
2747 		error = complete_walk(nd);
2748 		if (error)
2749 			return error;
2750 		audit_inode(name, dir, 0);
2751 		goto finish_open;
2752 	}
2753 
2754 	if (!(open_flag & O_CREAT)) {
2755 		if (nd->last.name[nd->last.len])
2756 			nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
2757 		if (open_flag & O_PATH && !(nd->flags & LOOKUP_FOLLOW))
2758 			symlink_ok = true;
2759 		/* we _can_ be in RCU mode here */
2760 		error = lookup_fast(nd, path, &inode);
2761 		if (likely(!error))
2762 			goto finish_lookup;
2763 
2764 		if (error < 0)
2765 			goto out;
2766 
2767 		BUG_ON(nd->inode != dir->d_inode);
2768 	} else {
2769 		/* create side of things */
2770 		/*
2771 		 * This will *only* deal with leaving RCU mode - LOOKUP_JUMPED
2772 		 * has been cleared when we got to the last component we are
2773 		 * about to look up
2774 		 */
2775 		error = complete_walk(nd);
2776 		if (error)
2777 			return error;
2778 
2779 		audit_inode(name, dir, LOOKUP_PARENT);
2780 		error = -EISDIR;
2781 		/* trailing slashes? */
2782 		if (nd->last.name[nd->last.len])
2783 			goto out;
2784 	}
2785 
2786 retry_lookup:
2787 	if (op->open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) {
2788 		error = mnt_want_write(nd->path.mnt);
2789 		if (!error)
2790 			got_write = true;
2791 		/*
2792 		 * do _not_ fail yet - we might not need that or fail with
2793 		 * a different error; let lookup_open() decide; we'll be
2794 		 * dropping this one anyway.
2795 		 */
2796 	}
2797 	mutex_lock(&dir->d_inode->i_mutex);
2798 	error = lookup_open(nd, path, file, op, got_write, opened);
2799 	mutex_unlock(&dir->d_inode->i_mutex);
2800 
2801 	if (error <= 0) {
2802 		if (error)
2803 			goto out;
2804 
2805 		if ((*opened & FILE_CREATED) ||
2806 		    !S_ISREG(file_inode(file)->i_mode))
2807 			will_truncate = false;
2808 
2809 		audit_inode(name, file->f_path.dentry, 0);
2810 		goto opened;
2811 	}
2812 
2813 	if (*opened & FILE_CREATED) {
2814 		/* Don't check for write permission, don't truncate */
2815 		open_flag &= ~O_TRUNC;
2816 		will_truncate = false;
2817 		acc_mode = MAY_OPEN;
2818 		path_to_nameidata(path, nd);
2819 		goto finish_open_created;
2820 	}
2821 
2822 	/*
2823 	 * create/update audit record if it already exists.
2824 	 */
2825 	if (path->dentry->d_inode)
2826 		audit_inode(name, path->dentry, 0);
2827 
2828 	/*
2829 	 * If atomic_open() acquired write access it is dropped now due to
2830 	 * possible mount and symlink following (this might be optimized away if
2831 	 * necessary...)
2832 	 */
2833 	if (got_write) {
2834 		mnt_drop_write(nd->path.mnt);
2835 		got_write = false;
2836 	}
2837 
2838 	error = -EEXIST;
2839 	if ((open_flag & (O_EXCL | O_CREAT)) == (O_EXCL | O_CREAT))
2840 		goto exit_dput;
2841 
2842 	error = follow_managed(path, nd->flags);
2843 	if (error < 0)
2844 		goto exit_dput;
2845 
2846 	if (error)
2847 		nd->flags |= LOOKUP_JUMPED;
2848 
2849 	BUG_ON(nd->flags & LOOKUP_RCU);
2850 	inode = path->dentry->d_inode;
2851 finish_lookup:
2852 	/* we _can_ be in RCU mode here */
2853 	error = -ENOENT;
2854 	if (!inode) {
2855 		path_to_nameidata(path, nd);
2856 		goto out;
2857 	}
2858 
2859 	if (should_follow_link(inode, !symlink_ok)) {
2860 		if (nd->flags & LOOKUP_RCU) {
2861 			if (unlikely(unlazy_walk(nd, path->dentry))) {
2862 				error = -ECHILD;
2863 				goto out;
2864 			}
2865 		}
2866 		BUG_ON(inode != path->dentry->d_inode);
2867 		return 1;
2868 	}
2869 
2870 	if ((nd->flags & LOOKUP_RCU) || nd->path.mnt != path->mnt) {
2871 		path_to_nameidata(path, nd);
2872 	} else {
2873 		save_parent.dentry = nd->path.dentry;
2874 		save_parent.mnt = mntget(path->mnt);
2875 		nd->path.dentry = path->dentry;
2876 
2877 	}
2878 	nd->inode = inode;
2879 	/* Why this, you ask?  _Now_ we might have grown LOOKUP_JUMPED... */
2880 	error = complete_walk(nd);
2881 	if (error) {
2882 		path_put(&save_parent);
2883 		return error;
2884 	}
2885 	error = -EISDIR;
2886 	if ((open_flag & O_CREAT) && S_ISDIR(nd->inode->i_mode))
2887 		goto out;
2888 	error = -ENOTDIR;
2889 	if ((nd->flags & LOOKUP_DIRECTORY) && !can_lookup(nd->inode))
2890 		goto out;
2891 	audit_inode(name, nd->path.dentry, 0);
2892 finish_open:
2893 	if (!S_ISREG(nd->inode->i_mode))
2894 		will_truncate = false;
2895 
2896 	if (will_truncate) {
2897 		error = mnt_want_write(nd->path.mnt);
2898 		if (error)
2899 			goto out;
2900 		got_write = true;
2901 	}
2902 finish_open_created:
2903 	error = may_open(&nd->path, acc_mode, open_flag);
2904 	if (error)
2905 		goto out;
2906 	file->f_path.mnt = nd->path.mnt;
2907 	error = finish_open(file, nd->path.dentry, NULL, opened);
2908 	if (error) {
2909 		if (error == -EOPENSTALE)
2910 			goto stale_open;
2911 		goto out;
2912 	}
2913 opened:
2914 	error = open_check_o_direct(file);
2915 	if (error)
2916 		goto exit_fput;
2917 	error = ima_file_check(file, op->acc_mode);
2918 	if (error)
2919 		goto exit_fput;
2920 
2921 	if (will_truncate) {
2922 		error = handle_truncate(file);
2923 		if (error)
2924 			goto exit_fput;
2925 	}
2926 out:
2927 	if (got_write)
2928 		mnt_drop_write(nd->path.mnt);
2929 	path_put(&save_parent);
2930 	terminate_walk(nd);
2931 	return error;
2932 
2933 exit_dput:
2934 	path_put_conditional(path, nd);
2935 	goto out;
2936 exit_fput:
2937 	fput(file);
2938 	goto out;
2939 
2940 stale_open:
2941 	/* If no saved parent or already retried then can't retry */
2942 	if (!save_parent.dentry || retried)
2943 		goto out;
2944 
2945 	BUG_ON(save_parent.dentry != dir);
2946 	path_put(&nd->path);
2947 	nd->path = save_parent;
2948 	nd->inode = dir->d_inode;
2949 	save_parent.mnt = NULL;
2950 	save_parent.dentry = NULL;
2951 	if (got_write) {
2952 		mnt_drop_write(nd->path.mnt);
2953 		got_write = false;
2954 	}
2955 	retried = true;
2956 	goto retry_lookup;
2957 }
2958 
path_openat(int dfd,struct filename * pathname,struct nameidata * nd,const struct open_flags * op,int flags)2959 static struct file *path_openat(int dfd, struct filename *pathname,
2960 		struct nameidata *nd, const struct open_flags *op, int flags)
2961 {
2962 	struct file *base = NULL;
2963 	struct file *file;
2964 	struct path path;
2965 	int opened = 0;
2966 	int error;
2967 
2968 	file = get_empty_filp();
2969 	if (IS_ERR(file))
2970 		return file;
2971 
2972 	file->f_flags = op->open_flag;
2973 
2974 	error = path_init(dfd, pathname->name, flags | LOOKUP_PARENT, nd, &base);
2975 	if (unlikely(error))
2976 		goto out;
2977 
2978 	current->total_link_count = 0;
2979 	error = link_path_walk(pathname->name, nd);
2980 	if (unlikely(error))
2981 		goto out;
2982 
2983 	error = do_last(nd, &path, file, op, &opened, pathname);
2984 	while (unlikely(error > 0)) { /* trailing symlink */
2985 		struct path link = path;
2986 		void *cookie;
2987 		if (!(nd->flags & LOOKUP_FOLLOW)) {
2988 			path_put_conditional(&path, nd);
2989 			path_put(&nd->path);
2990 			error = -ELOOP;
2991 			break;
2992 		}
2993 		error = may_follow_link(&link, nd);
2994 		if (unlikely(error))
2995 			break;
2996 		nd->flags |= LOOKUP_PARENT;
2997 		nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
2998 		error = follow_link(&link, nd, &cookie);
2999 		if (unlikely(error))
3000 			break;
3001 		error = do_last(nd, &path, file, op, &opened, pathname);
3002 		put_link(nd, &link, cookie);
3003 	}
3004 out:
3005 	if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT))
3006 		path_put(&nd->root);
3007 	if (base)
3008 		fput(base);
3009 	if (!(opened & FILE_OPENED)) {
3010 		BUG_ON(!error);
3011 		put_filp(file);
3012 	}
3013 	if (unlikely(error)) {
3014 		if (error == -EOPENSTALE) {
3015 			if (flags & LOOKUP_RCU)
3016 				error = -ECHILD;
3017 			else
3018 				error = -ESTALE;
3019 		}
3020 		file = ERR_PTR(error);
3021 	}
3022 	return file;
3023 }
3024 
do_filp_open(int dfd,struct filename * pathname,const struct open_flags * op,int flags)3025 struct file *do_filp_open(int dfd, struct filename *pathname,
3026 		const struct open_flags *op, int flags)
3027 {
3028 	struct nameidata nd;
3029 	struct file *filp;
3030 
3031 	filp = path_openat(dfd, pathname, &nd, op, flags | LOOKUP_RCU);
3032 	if (unlikely(filp == ERR_PTR(-ECHILD)))
3033 		filp = path_openat(dfd, pathname, &nd, op, flags);
3034 	if (unlikely(filp == ERR_PTR(-ESTALE)))
3035 		filp = path_openat(dfd, pathname, &nd, op, flags | LOOKUP_REVAL);
3036 	return filp;
3037 }
3038 
do_file_open_root(struct dentry * dentry,struct vfsmount * mnt,const char * name,const struct open_flags * op,int flags)3039 struct file *do_file_open_root(struct dentry *dentry, struct vfsmount *mnt,
3040 		const char *name, const struct open_flags *op, int flags)
3041 {
3042 	struct nameidata nd;
3043 	struct file *file;
3044 	struct filename filename = { .name = name };
3045 
3046 	nd.root.mnt = mnt;
3047 	nd.root.dentry = dentry;
3048 
3049 	flags |= LOOKUP_ROOT;
3050 
3051 	if (dentry->d_inode->i_op->follow_link && op->intent & LOOKUP_OPEN)
3052 		return ERR_PTR(-ELOOP);
3053 
3054 	file = path_openat(-1, &filename, &nd, op, flags | LOOKUP_RCU);
3055 	if (unlikely(file == ERR_PTR(-ECHILD)))
3056 		file = path_openat(-1, &filename, &nd, op, flags);
3057 	if (unlikely(file == ERR_PTR(-ESTALE)))
3058 		file = path_openat(-1, &filename, &nd, op, flags | LOOKUP_REVAL);
3059 	return file;
3060 }
3061 
kern_path_create(int dfd,const char * pathname,struct path * path,unsigned int lookup_flags)3062 struct dentry *kern_path_create(int dfd, const char *pathname,
3063 				struct path *path, unsigned int lookup_flags)
3064 {
3065 	struct dentry *dentry = ERR_PTR(-EEXIST);
3066 	struct nameidata nd;
3067 	int err2;
3068 	int error;
3069 	bool is_dir = (lookup_flags & LOOKUP_DIRECTORY);
3070 
3071 	/*
3072 	 * Note that only LOOKUP_REVAL and LOOKUP_DIRECTORY matter here. Any
3073 	 * other flags passed in are ignored!
3074 	 */
3075 	lookup_flags &= LOOKUP_REVAL;
3076 
3077 	error = do_path_lookup(dfd, pathname, LOOKUP_PARENT|lookup_flags, &nd);
3078 	if (error)
3079 		return ERR_PTR(error);
3080 
3081 	/*
3082 	 * Yucky last component or no last component at all?
3083 	 * (foo/., foo/.., /////)
3084 	 */
3085 	if (nd.last_type != LAST_NORM)
3086 		goto out;
3087 	nd.flags &= ~LOOKUP_PARENT;
3088 	nd.flags |= LOOKUP_CREATE | LOOKUP_EXCL;
3089 
3090 	/* don't fail immediately if it's r/o, at least try to report other errors */
3091 	err2 = mnt_want_write(nd.path.mnt);
3092 	/*
3093 	 * Do the final lookup.
3094 	 */
3095 	mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
3096 	dentry = lookup_hash(&nd);
3097 	if (IS_ERR(dentry))
3098 		goto unlock;
3099 
3100 	error = -EEXIST;
3101 	if (dentry->d_inode)
3102 		goto fail;
3103 	/*
3104 	 * Special case - lookup gave negative, but... we had foo/bar/
3105 	 * From the vfs_mknod() POV we just have a negative dentry -
3106 	 * all is fine. Let's be bastards - you had / on the end, you've
3107 	 * been asking for (non-existent) directory. -ENOENT for you.
3108 	 */
3109 	if (unlikely(!is_dir && nd.last.name[nd.last.len])) {
3110 		error = -ENOENT;
3111 		goto fail;
3112 	}
3113 	if (unlikely(err2)) {
3114 		error = err2;
3115 		goto fail;
3116 	}
3117 	*path = nd.path;
3118 	return dentry;
3119 fail:
3120 	dput(dentry);
3121 	dentry = ERR_PTR(error);
3122 unlock:
3123 	mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
3124 	if (!err2)
3125 		mnt_drop_write(nd.path.mnt);
3126 out:
3127 	path_put(&nd.path);
3128 	return dentry;
3129 }
3130 EXPORT_SYMBOL(kern_path_create);
3131 
done_path_create(struct path * path,struct dentry * dentry)3132 void done_path_create(struct path *path, struct dentry *dentry)
3133 {
3134 	dput(dentry);
3135 	mutex_unlock(&path->dentry->d_inode->i_mutex);
3136 	mnt_drop_write(path->mnt);
3137 	path_put(path);
3138 }
3139 EXPORT_SYMBOL(done_path_create);
3140 
user_path_create(int dfd,const char __user * pathname,struct path * path,unsigned int lookup_flags)3141 struct dentry *user_path_create(int dfd, const char __user *pathname,
3142 				struct path *path, unsigned int lookup_flags)
3143 {
3144 	struct filename *tmp = getname(pathname);
3145 	struct dentry *res;
3146 	if (IS_ERR(tmp))
3147 		return ERR_CAST(tmp);
3148 	res = kern_path_create(dfd, tmp->name, path, lookup_flags);
3149 	putname(tmp);
3150 	return res;
3151 }
3152 EXPORT_SYMBOL(user_path_create);
3153 
vfs_mknod2(struct vfsmount * mnt,struct inode * dir,struct dentry * dentry,umode_t mode,dev_t dev)3154 int vfs_mknod2(struct vfsmount *mnt, struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
3155 {
3156 	int error = may_create(mnt, dir, dentry);
3157 
3158 	if (error)
3159 		return error;
3160 
3161 	if ((S_ISCHR(mode) || S_ISBLK(mode)) && !capable(CAP_MKNOD))
3162 		return -EPERM;
3163 
3164 	if (!dir->i_op->mknod)
3165 		return -EPERM;
3166 
3167 	error = devcgroup_inode_mknod(mode, dev);
3168 	if (error)
3169 		return error;
3170 
3171 	error = security_inode_mknod(dir, dentry, mode, dev);
3172 	if (error)
3173 		return error;
3174 
3175 	error = dir->i_op->mknod(dir, dentry, mode, dev);
3176 	if (!error)
3177 		fsnotify_create(dir, dentry);
3178 	return error;
3179 }
3180 EXPORT_SYMBOL(vfs_mknod2);
3181 
vfs_mknod(struct inode * dir,struct dentry * dentry,umode_t mode,dev_t dev)3182 int vfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
3183 {
3184 	return vfs_mknod2(NULL, dir, dentry, mode, dev);
3185 }
3186 EXPORT_SYMBOL(vfs_mknod);
3187 
may_mknod(umode_t mode)3188 static int may_mknod(umode_t mode)
3189 {
3190 	switch (mode & S_IFMT) {
3191 	case S_IFREG:
3192 	case S_IFCHR:
3193 	case S_IFBLK:
3194 	case S_IFIFO:
3195 	case S_IFSOCK:
3196 	case 0: /* zero mode translates to S_IFREG */
3197 		return 0;
3198 	case S_IFDIR:
3199 		return -EPERM;
3200 	default:
3201 		return -EINVAL;
3202 	}
3203 }
3204 
SYSCALL_DEFINE4(mknodat,int,dfd,const char __user *,filename,umode_t,mode,unsigned,dev)3205 SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode,
3206 		unsigned, dev)
3207 {
3208 	struct dentry *dentry;
3209 	struct path path;
3210 	int error;
3211 	unsigned int lookup_flags = 0;
3212 
3213 	error = may_mknod(mode);
3214 	if (error)
3215 		return error;
3216 retry:
3217 	dentry = user_path_create(dfd, filename, &path, lookup_flags);
3218 	if (IS_ERR(dentry))
3219 		return PTR_ERR(dentry);
3220 
3221 	if (!IS_POSIXACL(path.dentry->d_inode))
3222 		mode &= ~current_umask();
3223 	error = security_path_mknod(&path, dentry, mode, dev);
3224 	if (error)
3225 		goto out;
3226 	switch (mode & S_IFMT) {
3227 		case 0: case S_IFREG:
3228 			error = vfs_create2(path.mnt, path.dentry->d_inode,dentry,mode,true);
3229 			break;
3230 		case S_IFCHR: case S_IFBLK:
3231 			error = vfs_mknod2(path.mnt, path.dentry->d_inode,dentry,mode,
3232 					new_decode_dev(dev));
3233 			break;
3234 		case S_IFIFO: case S_IFSOCK:
3235 			error = vfs_mknod(path.dentry->d_inode,dentry,mode,0);
3236 			break;
3237 	}
3238 out:
3239 	done_path_create(&path, dentry);
3240 	if (retry_estale(error, lookup_flags)) {
3241 		lookup_flags |= LOOKUP_REVAL;
3242 		goto retry;
3243 	}
3244 	return error;
3245 }
3246 
SYSCALL_DEFINE3(mknod,const char __user *,filename,umode_t,mode,unsigned,dev)3247 SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
3248 {
3249 	return sys_mknodat(AT_FDCWD, filename, mode, dev);
3250 }
3251 
vfs_mkdir2(struct vfsmount * mnt,struct inode * dir,struct dentry * dentry,umode_t mode)3252 int vfs_mkdir2(struct vfsmount *mnt, struct inode *dir, struct dentry *dentry, umode_t mode)
3253 {
3254 	int error = may_create(mnt, dir, dentry);
3255 	unsigned max_links = dir->i_sb->s_max_links;
3256 
3257 	if (error)
3258 		return error;
3259 
3260 	if (!dir->i_op->mkdir)
3261 		return -EPERM;
3262 
3263 	mode &= (S_IRWXUGO|S_ISVTX);
3264 	error = security_inode_mkdir(dir, dentry, mode);
3265 	if (error)
3266 		return error;
3267 
3268 	if (max_links && dir->i_nlink >= max_links)
3269 		return -EMLINK;
3270 
3271 	error = dir->i_op->mkdir(dir, dentry, mode);
3272 	if (!error)
3273 		fsnotify_mkdir(dir, dentry);
3274 	return error;
3275 }
3276 EXPORT_SYMBOL(vfs_mkdir2);
3277 
vfs_mkdir(struct inode * dir,struct dentry * dentry,umode_t mode)3278 int vfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
3279 {
3280 	return vfs_mkdir2(NULL, dir, dentry, mode);
3281 }
3282 EXPORT_SYMBOL(vfs_mkdir);
3283 
SYSCALL_DEFINE3(mkdirat,int,dfd,const char __user *,pathname,umode_t,mode)3284 SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode)
3285 {
3286 	struct dentry *dentry;
3287 	struct path path;
3288 	int error;
3289 	unsigned int lookup_flags = LOOKUP_DIRECTORY;
3290 
3291 retry:
3292 	dentry = user_path_create(dfd, pathname, &path, lookup_flags);
3293 	if (IS_ERR(dentry))
3294 		return PTR_ERR(dentry);
3295 
3296 	if (!IS_POSIXACL(path.dentry->d_inode))
3297 		mode &= ~current_umask();
3298 	error = security_path_mkdir(&path, dentry, mode);
3299 	if (!error)
3300 		error = vfs_mkdir2(path.mnt, path.dentry->d_inode, dentry, mode);
3301 	done_path_create(&path, dentry);
3302 	if (retry_estale(error, lookup_flags)) {
3303 		lookup_flags |= LOOKUP_REVAL;
3304 		goto retry;
3305 	}
3306 	return error;
3307 }
3308 
SYSCALL_DEFINE2(mkdir,const char __user *,pathname,umode_t,mode)3309 SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode)
3310 {
3311 	return sys_mkdirat(AT_FDCWD, pathname, mode);
3312 }
3313 
3314 /*
3315  * The dentry_unhash() helper will try to drop the dentry early: we
3316  * should have a usage count of 1 if we're the only user of this
3317  * dentry, and if that is true (possibly after pruning the dcache),
3318  * then we drop the dentry now.
3319  *
3320  * A low-level filesystem can, if it choses, legally
3321  * do a
3322  *
3323  *	if (!d_unhashed(dentry))
3324  *		return -EBUSY;
3325  *
3326  * if it cannot handle the case of removing a directory
3327  * that is still in use by something else..
3328  */
dentry_unhash(struct dentry * dentry)3329 void dentry_unhash(struct dentry *dentry)
3330 {
3331 	shrink_dcache_parent(dentry);
3332 	spin_lock(&dentry->d_lock);
3333 	if (dentry->d_count == 1)
3334 		__d_drop(dentry);
3335 	spin_unlock(&dentry->d_lock);
3336 }
3337 
vfs_rmdir2(struct vfsmount * mnt,struct inode * dir,struct dentry * dentry)3338 int vfs_rmdir2(struct vfsmount *mnt, struct inode *dir, struct dentry *dentry)
3339 {
3340 	int error = may_delete(mnt, dir, dentry, 1);
3341 
3342 	if (error)
3343 		return error;
3344 
3345 	if (!dir->i_op->rmdir)
3346 		return -EPERM;
3347 
3348 	dget(dentry);
3349 	mutex_lock(&dentry->d_inode->i_mutex);
3350 
3351 	error = -EBUSY;
3352 	if (d_mountpoint(dentry))
3353 		goto out;
3354 
3355 	error = security_inode_rmdir(dir, dentry);
3356 	if (error)
3357 		goto out;
3358 
3359 	shrink_dcache_parent(dentry);
3360 	error = dir->i_op->rmdir(dir, dentry);
3361 	if (error)
3362 		goto out;
3363 
3364 	dentry->d_inode->i_flags |= S_DEAD;
3365 	dont_mount(dentry);
3366 
3367 out:
3368 	mutex_unlock(&dentry->d_inode->i_mutex);
3369 	dput(dentry);
3370 	if (!error)
3371 		d_delete(dentry);
3372 	return error;
3373 }
3374 EXPORT_SYMBOL(vfs_rmdir2);
3375 
vfs_rmdir(struct inode * dir,struct dentry * dentry)3376 int vfs_rmdir(struct inode *dir, struct dentry *dentry)
3377 {
3378 	return vfs_rmdir2(NULL, dir, dentry);
3379 }
3380 EXPORT_SYMBOL(vfs_rmdir);
3381 
do_rmdir(int dfd,const char __user * pathname)3382 static long do_rmdir(int dfd, const char __user *pathname)
3383 {
3384 	int error = 0;
3385 	struct filename *name;
3386 	struct dentry *dentry;
3387 	struct nameidata nd;
3388 	unsigned int lookup_flags = 0;
3389 retry:
3390 	name = user_path_parent(dfd, pathname, &nd, lookup_flags);
3391 	if (IS_ERR(name))
3392 		return PTR_ERR(name);
3393 
3394 	switch(nd.last_type) {
3395 	case LAST_DOTDOT:
3396 		error = -ENOTEMPTY;
3397 		goto exit1;
3398 	case LAST_DOT:
3399 		error = -EINVAL;
3400 		goto exit1;
3401 	case LAST_ROOT:
3402 		error = -EBUSY;
3403 		goto exit1;
3404 	}
3405 
3406 	nd.flags &= ~LOOKUP_PARENT;
3407 	error = mnt_want_write(nd.path.mnt);
3408 	if (error)
3409 		goto exit1;
3410 
3411 	mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
3412 	dentry = lookup_hash(&nd);
3413 	error = PTR_ERR(dentry);
3414 	if (IS_ERR(dentry))
3415 		goto exit2;
3416 	if (!dentry->d_inode) {
3417 		error = -ENOENT;
3418 		goto exit3;
3419 	}
3420 	error = security_path_rmdir(&nd.path, dentry);
3421 	if (error)
3422 		goto exit3;
3423 	error = vfs_rmdir2(nd.path.mnt, nd.path.dentry->d_inode, dentry);
3424 exit3:
3425 	dput(dentry);
3426 exit2:
3427 	mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
3428 	mnt_drop_write(nd.path.mnt);
3429 exit1:
3430 	path_put(&nd.path);
3431 	putname(name);
3432 	if (retry_estale(error, lookup_flags)) {
3433 		lookup_flags |= LOOKUP_REVAL;
3434 		goto retry;
3435 	}
3436 	return error;
3437 }
3438 
SYSCALL_DEFINE1(rmdir,const char __user *,pathname)3439 SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
3440 {
3441 	return do_rmdir(AT_FDCWD, pathname);
3442 }
3443 
vfs_unlink2(struct vfsmount * mnt,struct inode * dir,struct dentry * dentry)3444 int vfs_unlink2(struct vfsmount *mnt, struct inode *dir, struct dentry *dentry)
3445 {
3446 	int error = may_delete(mnt, dir, dentry, 0);
3447 
3448 	if (error)
3449 		return error;
3450 
3451 	if (!dir->i_op->unlink)
3452 		return -EPERM;
3453 
3454 	mutex_lock(&dentry->d_inode->i_mutex);
3455 	if (d_mountpoint(dentry))
3456 		error = -EBUSY;
3457 	else {
3458 		error = security_inode_unlink(dir, dentry);
3459 		if (!error) {
3460 			error = dir->i_op->unlink(dir, dentry);
3461 			if (!error)
3462 				dont_mount(dentry);
3463 		}
3464 	}
3465 	mutex_unlock(&dentry->d_inode->i_mutex);
3466 
3467 	/* We don't d_delete() NFS sillyrenamed files--they still exist. */
3468 	if (!error && !(dentry->d_flags & DCACHE_NFSFS_RENAMED)) {
3469 		fsnotify_link_count(dentry->d_inode);
3470 		d_delete(dentry);
3471 	}
3472 
3473 	return error;
3474 }
3475 EXPORT_SYMBOL(vfs_unlink2);
3476 
vfs_unlink(struct inode * dir,struct dentry * dentry)3477 int vfs_unlink(struct inode *dir, struct dentry *dentry)
3478 {
3479 	return vfs_unlink2(NULL, dir, dentry);
3480 }
3481 EXPORT_SYMBOL(vfs_unlink);
3482 
3483 /*
3484  * Make sure that the actual truncation of the file will occur outside its
3485  * directory's i_mutex.  Truncate can take a long time if there is a lot of
3486  * writeout happening, and we don't want to prevent access to the directory
3487  * while waiting on the I/O.
3488  */
do_unlinkat(int dfd,const char __user * pathname)3489 static long do_unlinkat(int dfd, const char __user *pathname)
3490 {
3491 	int error;
3492 	struct filename *name;
3493 	struct dentry *dentry;
3494 	struct nameidata nd;
3495 	struct inode *inode = NULL;
3496 	unsigned int lookup_flags = 0;
3497 retry:
3498 	name = user_path_parent(dfd, pathname, &nd, lookup_flags);
3499 	if (IS_ERR(name))
3500 		return PTR_ERR(name);
3501 
3502 	error = -EISDIR;
3503 	if (nd.last_type != LAST_NORM)
3504 		goto exit1;
3505 
3506 	nd.flags &= ~LOOKUP_PARENT;
3507 	error = mnt_want_write(nd.path.mnt);
3508 	if (error)
3509 		goto exit1;
3510 
3511 	mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
3512 	dentry = lookup_hash(&nd);
3513 	error = PTR_ERR(dentry);
3514 	if (!IS_ERR(dentry)) {
3515 		/* Why not before? Because we want correct error value */
3516 		if (nd.last.name[nd.last.len])
3517 			goto slashes;
3518 		inode = dentry->d_inode;
3519 		if (!inode)
3520 			goto slashes;
3521 		ihold(inode);
3522 		error = security_path_unlink(&nd.path, dentry);
3523 		if (error)
3524 			goto exit2;
3525 		error = vfs_unlink2(nd.path.mnt, nd.path.dentry->d_inode, dentry);
3526 exit2:
3527 		dput(dentry);
3528 	}
3529 	mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
3530 	if (inode)
3531 		iput(inode);	/* truncate the inode here */
3532 	mnt_drop_write(nd.path.mnt);
3533 exit1:
3534 	path_put(&nd.path);
3535 	putname(name);
3536 	if (retry_estale(error, lookup_flags)) {
3537 		lookup_flags |= LOOKUP_REVAL;
3538 		inode = NULL;
3539 		goto retry;
3540 	}
3541 	return error;
3542 
3543 slashes:
3544 	error = !dentry->d_inode ? -ENOENT :
3545 		S_ISDIR(dentry->d_inode->i_mode) ? -EISDIR : -ENOTDIR;
3546 	goto exit2;
3547 }
3548 
SYSCALL_DEFINE3(unlinkat,int,dfd,const char __user *,pathname,int,flag)3549 SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
3550 {
3551 	if ((flag & ~AT_REMOVEDIR) != 0)
3552 		return -EINVAL;
3553 
3554 	if (flag & AT_REMOVEDIR)
3555 		return do_rmdir(dfd, pathname);
3556 
3557 	return do_unlinkat(dfd, pathname);
3558 }
3559 
SYSCALL_DEFINE1(unlink,const char __user *,pathname)3560 SYSCALL_DEFINE1(unlink, const char __user *, pathname)
3561 {
3562 	return do_unlinkat(AT_FDCWD, pathname);
3563 }
3564 
vfs_symlink2(struct vfsmount * mnt,struct inode * dir,struct dentry * dentry,const char * oldname)3565 int vfs_symlink2(struct vfsmount *mnt, struct inode *dir, struct dentry *dentry, const char *oldname)
3566 {
3567 	int error = may_create(mnt, dir, dentry);
3568 
3569 	if (error)
3570 		return error;
3571 
3572 	if (!dir->i_op->symlink)
3573 		return -EPERM;
3574 
3575 	error = security_inode_symlink(dir, dentry, oldname);
3576 	if (error)
3577 		return error;
3578 
3579 	error = dir->i_op->symlink(dir, dentry, oldname);
3580 	if (!error)
3581 		fsnotify_create(dir, dentry);
3582 	return error;
3583 }
3584 EXPORT_SYMBOL(vfs_symlink2);
3585 
vfs_symlink(struct inode * dir,struct dentry * dentry,const char * oldname)3586 int vfs_symlink(struct inode *dir, struct dentry *dentry, const char *oldname)
3587 {
3588 	return vfs_symlink2(NULL, dir, dentry, oldname);
3589 }
3590 EXPORT_SYMBOL(vfs_symlink);
3591 
SYSCALL_DEFINE3(symlinkat,const char __user *,oldname,int,newdfd,const char __user *,newname)3592 SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
3593 		int, newdfd, const char __user *, newname)
3594 {
3595 	int error;
3596 	struct filename *from;
3597 	struct dentry *dentry;
3598 	struct path path;
3599 	unsigned int lookup_flags = 0;
3600 
3601 	from = getname(oldname);
3602 	if (IS_ERR(from))
3603 		return PTR_ERR(from);
3604 retry:
3605 	dentry = user_path_create(newdfd, newname, &path, lookup_flags);
3606 	error = PTR_ERR(dentry);
3607 	if (IS_ERR(dentry))
3608 		goto out_putname;
3609 
3610 	error = security_path_symlink(&path, dentry, from->name);
3611 	if (!error)
3612 		error = vfs_symlink2(path.mnt, path.dentry->d_inode, dentry, from->name);
3613 	done_path_create(&path, dentry);
3614 	if (retry_estale(error, lookup_flags)) {
3615 		lookup_flags |= LOOKUP_REVAL;
3616 		goto retry;
3617 	}
3618 out_putname:
3619 	putname(from);
3620 	return error;
3621 }
3622 
SYSCALL_DEFINE2(symlink,const char __user *,oldname,const char __user *,newname)3623 SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
3624 {
3625 	return sys_symlinkat(oldname, AT_FDCWD, newname);
3626 }
3627 
vfs_link2(struct vfsmount * mnt,struct dentry * old_dentry,struct inode * dir,struct dentry * new_dentry)3628 int vfs_link2(struct vfsmount *mnt, struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
3629 {
3630 	struct inode *inode = old_dentry->d_inode;
3631 	unsigned max_links = dir->i_sb->s_max_links;
3632 	int error;
3633 
3634 	if (!inode)
3635 		return -ENOENT;
3636 
3637 	error = may_create(mnt, dir, new_dentry);
3638 	if (error)
3639 		return error;
3640 
3641 	if (dir->i_sb != inode->i_sb)
3642 		return -EXDEV;
3643 
3644 	/*
3645 	 * A link to an append-only or immutable file cannot be created.
3646 	 */
3647 	if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
3648 		return -EPERM;
3649 	if (!dir->i_op->link)
3650 		return -EPERM;
3651 	if (S_ISDIR(inode->i_mode))
3652 		return -EPERM;
3653 
3654 	error = security_inode_link(old_dentry, dir, new_dentry);
3655 	if (error)
3656 		return error;
3657 
3658 	mutex_lock(&inode->i_mutex);
3659 	/* Make sure we don't allow creating hardlink to an unlinked file */
3660 	if (inode->i_nlink == 0)
3661 		error =  -ENOENT;
3662 	else if (max_links && inode->i_nlink >= max_links)
3663 		error = -EMLINK;
3664 	else
3665 		error = dir->i_op->link(old_dentry, dir, new_dentry);
3666 	mutex_unlock(&inode->i_mutex);
3667 	if (!error)
3668 		fsnotify_link(dir, inode, new_dentry);
3669 	return error;
3670 }
3671 EXPORT_SYMBOL(vfs_link2);
3672 
vfs_link(struct dentry * old_dentry,struct inode * dir,struct dentry * new_dentry)3673 int vfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
3674 {
3675 	return vfs_link2(NULL, old_dentry, dir, new_dentry);
3676 }
3677 EXPORT_SYMBOL(vfs_link);
3678 
3679 /*
3680  * Hardlinks are often used in delicate situations.  We avoid
3681  * security-related surprises by not following symlinks on the
3682  * newname.  --KAB
3683  *
3684  * We don't follow them on the oldname either to be compatible
3685  * with linux 2.0, and to avoid hard-linking to directories
3686  * and other special files.  --ADM
3687  */
SYSCALL_DEFINE5(linkat,int,olddfd,const char __user *,oldname,int,newdfd,const char __user *,newname,int,flags)3688 SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
3689 		int, newdfd, const char __user *, newname, int, flags)
3690 {
3691 	struct dentry *new_dentry;
3692 	struct path old_path, new_path;
3693 	int how = 0;
3694 	int error;
3695 
3696 	if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0)
3697 		return -EINVAL;
3698 	/*
3699 	 * To use null names we require CAP_DAC_READ_SEARCH
3700 	 * This ensures that not everyone will be able to create
3701 	 * handlink using the passed filedescriptor.
3702 	 */
3703 	if (flags & AT_EMPTY_PATH) {
3704 		if (!capable(CAP_DAC_READ_SEARCH))
3705 			return -ENOENT;
3706 		how = LOOKUP_EMPTY;
3707 	}
3708 
3709 	if (flags & AT_SYMLINK_FOLLOW)
3710 		how |= LOOKUP_FOLLOW;
3711 retry:
3712 	error = user_path_at(olddfd, oldname, how, &old_path);
3713 	if (error)
3714 		return error;
3715 
3716 	new_dentry = user_path_create(newdfd, newname, &new_path,
3717 					(how & LOOKUP_REVAL));
3718 	error = PTR_ERR(new_dentry);
3719 	if (IS_ERR(new_dentry))
3720 		goto out;
3721 
3722 	error = -EXDEV;
3723 	if (old_path.mnt != new_path.mnt)
3724 		goto out_dput;
3725 	error = may_linkat(&old_path);
3726 	if (unlikely(error))
3727 		goto out_dput;
3728 	error = security_path_link(old_path.dentry, &new_path, new_dentry);
3729 	if (error)
3730 		goto out_dput;
3731 	error = vfs_link2(old_path.mnt, old_path.dentry, new_path.dentry->d_inode, new_dentry);
3732 out_dput:
3733 	done_path_create(&new_path, new_dentry);
3734 	if (retry_estale(error, how)) {
3735 		how |= LOOKUP_REVAL;
3736 		goto retry;
3737 	}
3738 out:
3739 	path_put(&old_path);
3740 
3741 	return error;
3742 }
3743 
SYSCALL_DEFINE2(link,const char __user *,oldname,const char __user *,newname)3744 SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
3745 {
3746 	return sys_linkat(AT_FDCWD, oldname, AT_FDCWD, newname, 0);
3747 }
3748 
3749 /*
3750  * The worst of all namespace operations - renaming directory. "Perverted"
3751  * doesn't even start to describe it. Somebody in UCB had a heck of a trip...
3752  * Problems:
3753  *	a) we can get into loop creation. Check is done in is_subdir().
3754  *	b) race potential - two innocent renames can create a loop together.
3755  *	   That's where 4.4 screws up. Current fix: serialization on
3756  *	   sb->s_vfs_rename_mutex. We might be more accurate, but that's another
3757  *	   story.
3758  *	c) we have to lock _three_ objects - parents and victim (if it exists).
3759  *	   And that - after we got ->i_mutex on parents (until then we don't know
3760  *	   whether the target exists).  Solution: try to be smart with locking
3761  *	   order for inodes.  We rely on the fact that tree topology may change
3762  *	   only under ->s_vfs_rename_mutex _and_ that parent of the object we
3763  *	   move will be locked.  Thus we can rank directories by the tree
3764  *	   (ancestors first) and rank all non-directories after them.
3765  *	   That works since everybody except rename does "lock parent, lookup,
3766  *	   lock child" and rename is under ->s_vfs_rename_mutex.
3767  *	   HOWEVER, it relies on the assumption that any object with ->lookup()
3768  *	   has no more than 1 dentry.  If "hybrid" objects will ever appear,
3769  *	   we'd better make sure that there's no link(2) for them.
3770  *	d) conversion from fhandle to dentry may come in the wrong moment - when
3771  *	   we are removing the target. Solution: we will have to grab ->i_mutex
3772  *	   in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
3773  *	   ->i_mutex on parents, which works but leads to some truly excessive
3774  *	   locking].
3775  */
vfs_rename_dir(struct vfsmount * mnt,struct inode * old_dir,struct dentry * old_dentry,struct inode * new_dir,struct dentry * new_dentry)3776 static int vfs_rename_dir(struct vfsmount *mnt,
3777 	       struct inode *old_dir, struct dentry *old_dentry,
3778 	       struct inode *new_dir, struct dentry *new_dentry)
3779 {
3780 	int error = 0;
3781 	struct inode *target = new_dentry->d_inode;
3782 	unsigned max_links = new_dir->i_sb->s_max_links;
3783 
3784 	/*
3785 	 * If we are going to change the parent - check write permissions,
3786 	 * we'll need to flip '..'.
3787 	 */
3788 	if (new_dir != old_dir) {
3789 		error = inode_permission2(mnt, old_dentry->d_inode, MAY_WRITE);
3790 		if (error)
3791 			return error;
3792 	}
3793 
3794 	error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry);
3795 	if (error)
3796 		return error;
3797 
3798 	dget(new_dentry);
3799 	if (target)
3800 		mutex_lock(&target->i_mutex);
3801 
3802 	error = -EBUSY;
3803 	if (d_mountpoint(old_dentry) || d_mountpoint(new_dentry))
3804 		goto out;
3805 
3806 	error = -EMLINK;
3807 	if (max_links && !target && new_dir != old_dir &&
3808 	    new_dir->i_nlink >= max_links)
3809 		goto out;
3810 
3811 	if (target)
3812 		shrink_dcache_parent(new_dentry);
3813 	error = old_dir->i_op->rename(old_dir, old_dentry, new_dir, new_dentry);
3814 	if (error)
3815 		goto out;
3816 
3817 	if (target) {
3818 		target->i_flags |= S_DEAD;
3819 		dont_mount(new_dentry);
3820 	}
3821 out:
3822 	if (target)
3823 		mutex_unlock(&target->i_mutex);
3824 	dput(new_dentry);
3825 	if (!error)
3826 		if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE))
3827 			d_move(old_dentry,new_dentry);
3828 	return error;
3829 }
3830 
vfs_rename_other(struct inode * old_dir,struct dentry * old_dentry,struct inode * new_dir,struct dentry * new_dentry)3831 static int vfs_rename_other(struct inode *old_dir, struct dentry *old_dentry,
3832 			    struct inode *new_dir, struct dentry *new_dentry)
3833 {
3834 	struct inode *target = new_dentry->d_inode;
3835 	int error;
3836 
3837 	error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry);
3838 	if (error)
3839 		return error;
3840 
3841 	dget(new_dentry);
3842 	if (target)
3843 		mutex_lock(&target->i_mutex);
3844 
3845 	error = -EBUSY;
3846 	if (d_mountpoint(old_dentry)||d_mountpoint(new_dentry))
3847 		goto out;
3848 
3849 	error = old_dir->i_op->rename(old_dir, old_dentry, new_dir, new_dentry);
3850 	if (error)
3851 		goto out;
3852 
3853 	if (target)
3854 		dont_mount(new_dentry);
3855 	if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE))
3856 		d_move(old_dentry, new_dentry);
3857 out:
3858 	if (target)
3859 		mutex_unlock(&target->i_mutex);
3860 	dput(new_dentry);
3861 	return error;
3862 }
3863 
vfs_rename2(struct vfsmount * mnt,struct inode * old_dir,struct dentry * old_dentry,struct inode * new_dir,struct dentry * new_dentry)3864 int vfs_rename2(struct vfsmount *mnt,
3865 	       struct inode *old_dir, struct dentry *old_dentry,
3866 	       struct inode *new_dir, struct dentry *new_dentry)
3867 {
3868 	int error;
3869 	int is_dir = S_ISDIR(old_dentry->d_inode->i_mode);
3870 	const unsigned char *old_name;
3871 
3872 	if (old_dentry->d_inode == new_dentry->d_inode)
3873  		return 0;
3874 
3875 	error = may_delete(mnt, old_dir, old_dentry, is_dir);
3876 	if (error)
3877 		return error;
3878 
3879 	if (!new_dentry->d_inode)
3880 		error = may_create(mnt, new_dir, new_dentry);
3881 	else
3882 		error = may_delete(mnt, new_dir, new_dentry, is_dir);
3883 	if (error)
3884 		return error;
3885 
3886 	if (!old_dir->i_op->rename)
3887 		return -EPERM;
3888 
3889 	old_name = fsnotify_oldname_init(old_dentry->d_name.name);
3890 
3891 	if (is_dir)
3892 		error = vfs_rename_dir(mnt, old_dir,old_dentry,new_dir,new_dentry);
3893 	else
3894 		error = vfs_rename_other(old_dir,old_dentry,new_dir,new_dentry);
3895 	if (!error)
3896 		fsnotify_move(old_dir, new_dir, old_name, is_dir,
3897 			      new_dentry->d_inode, old_dentry);
3898 	fsnotify_oldname_free(old_name);
3899 
3900 	return error;
3901 }
3902 EXPORT_SYMBOL(vfs_rename2);
3903 
vfs_rename(struct inode * old_dir,struct dentry * old_dentry,struct inode * new_dir,struct dentry * new_dentry)3904 int vfs_rename(struct inode *old_dir, struct dentry *old_dentry,
3905 	       struct inode *new_dir, struct dentry *new_dentry)
3906 {
3907 	return vfs_rename2(NULL, old_dir, old_dentry, new_dir, new_dentry);
3908 }
3909 EXPORT_SYMBOL(vfs_rename);
3910 
SYSCALL_DEFINE4(renameat,int,olddfd,const char __user *,oldname,int,newdfd,const char __user *,newname)3911 SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
3912 		int, newdfd, const char __user *, newname)
3913 {
3914 	struct dentry *old_dir, *new_dir;
3915 	struct dentry *old_dentry, *new_dentry;
3916 	struct dentry *trap;
3917 	struct nameidata oldnd, newnd;
3918 	struct filename *from;
3919 	struct filename *to;
3920 	unsigned int lookup_flags = 0;
3921 	bool should_retry = false;
3922 	int error;
3923 retry:
3924 	from = user_path_parent(olddfd, oldname, &oldnd, lookup_flags);
3925 	if (IS_ERR(from)) {
3926 		error = PTR_ERR(from);
3927 		goto exit;
3928 	}
3929 
3930 	to = user_path_parent(newdfd, newname, &newnd, lookup_flags);
3931 	if (IS_ERR(to)) {
3932 		error = PTR_ERR(to);
3933 		goto exit1;
3934 	}
3935 
3936 	error = -EXDEV;
3937 	if (oldnd.path.mnt != newnd.path.mnt)
3938 		goto exit2;
3939 
3940 	old_dir = oldnd.path.dentry;
3941 	error = -EBUSY;
3942 	if (oldnd.last_type != LAST_NORM)
3943 		goto exit2;
3944 
3945 	new_dir = newnd.path.dentry;
3946 	if (newnd.last_type != LAST_NORM)
3947 		goto exit2;
3948 
3949 	error = mnt_want_write(oldnd.path.mnt);
3950 	if (error)
3951 		goto exit2;
3952 
3953 	oldnd.flags &= ~LOOKUP_PARENT;
3954 	newnd.flags &= ~LOOKUP_PARENT;
3955 	newnd.flags |= LOOKUP_RENAME_TARGET;
3956 
3957 	trap = lock_rename(new_dir, old_dir);
3958 
3959 	old_dentry = lookup_hash(&oldnd);
3960 	error = PTR_ERR(old_dentry);
3961 	if (IS_ERR(old_dentry))
3962 		goto exit3;
3963 	/* source must exist */
3964 	error = -ENOENT;
3965 	if (!old_dentry->d_inode)
3966 		goto exit4;
3967 	/* unless the source is a directory trailing slashes give -ENOTDIR */
3968 	if (!S_ISDIR(old_dentry->d_inode->i_mode)) {
3969 		error = -ENOTDIR;
3970 		if (oldnd.last.name[oldnd.last.len])
3971 			goto exit4;
3972 		if (newnd.last.name[newnd.last.len])
3973 			goto exit4;
3974 	}
3975 	/* source should not be ancestor of target */
3976 	error = -EINVAL;
3977 	if (old_dentry == trap)
3978 		goto exit4;
3979 	new_dentry = lookup_hash(&newnd);
3980 	error = PTR_ERR(new_dentry);
3981 	if (IS_ERR(new_dentry))
3982 		goto exit4;
3983 	/* target should not be an ancestor of source */
3984 	error = -ENOTEMPTY;
3985 	if (new_dentry == trap)
3986 		goto exit5;
3987 
3988 	error = security_path_rename(&oldnd.path, old_dentry,
3989 				     &newnd.path, new_dentry);
3990 	if (error)
3991 		goto exit5;
3992 	error = vfs_rename2(oldnd.path.mnt, old_dir->d_inode, old_dentry,
3993 				   new_dir->d_inode, new_dentry);
3994 exit5:
3995 	dput(new_dentry);
3996 exit4:
3997 	dput(old_dentry);
3998 exit3:
3999 	unlock_rename(new_dir, old_dir);
4000 	mnt_drop_write(oldnd.path.mnt);
4001 exit2:
4002 	if (retry_estale(error, lookup_flags))
4003 		should_retry = true;
4004 	path_put(&newnd.path);
4005 	putname(to);
4006 exit1:
4007 	path_put(&oldnd.path);
4008 	putname(from);
4009 	if (should_retry) {
4010 		should_retry = false;
4011 		lookup_flags |= LOOKUP_REVAL;
4012 		goto retry;
4013 	}
4014 exit:
4015 	return error;
4016 }
4017 
SYSCALL_DEFINE2(rename,const char __user *,oldname,const char __user *,newname)4018 SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
4019 {
4020 	return sys_renameat(AT_FDCWD, oldname, AT_FDCWD, newname);
4021 }
4022 
vfs_readlink(struct dentry * dentry,char __user * buffer,int buflen,const char * link)4023 int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen, const char *link)
4024 {
4025 	int len;
4026 
4027 	len = PTR_ERR(link);
4028 	if (IS_ERR(link))
4029 		goto out;
4030 
4031 	len = strlen(link);
4032 	if (len > (unsigned) buflen)
4033 		len = buflen;
4034 	if (copy_to_user(buffer, link, len))
4035 		len = -EFAULT;
4036 out:
4037 	return len;
4038 }
4039 
4040 /*
4041  * A helper for ->readlink().  This should be used *ONLY* for symlinks that
4042  * have ->follow_link() touching nd only in nd_set_link().  Using (or not
4043  * using) it for any given inode is up to filesystem.
4044  */
generic_readlink(struct dentry * dentry,char __user * buffer,int buflen)4045 int generic_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4046 {
4047 	struct nameidata nd;
4048 	void *cookie;
4049 	int res;
4050 
4051 	nd.depth = 0;
4052 	cookie = dentry->d_inode->i_op->follow_link(dentry, &nd);
4053 	if (IS_ERR(cookie))
4054 		return PTR_ERR(cookie);
4055 
4056 	res = vfs_readlink(dentry, buffer, buflen, nd_get_link(&nd));
4057 	if (dentry->d_inode->i_op->put_link)
4058 		dentry->d_inode->i_op->put_link(dentry, &nd, cookie);
4059 	return res;
4060 }
4061 
vfs_follow_link(struct nameidata * nd,const char * link)4062 int vfs_follow_link(struct nameidata *nd, const char *link)
4063 {
4064 	return __vfs_follow_link(nd, link);
4065 }
4066 
4067 /* get the link contents into pagecache */
page_getlink(struct dentry * dentry,struct page ** ppage)4068 static char *page_getlink(struct dentry * dentry, struct page **ppage)
4069 {
4070 	char *kaddr;
4071 	struct page *page;
4072 	struct address_space *mapping = dentry->d_inode->i_mapping;
4073 	page = read_mapping_page(mapping, 0, NULL);
4074 	if (IS_ERR(page))
4075 		return (char*)page;
4076 	*ppage = page;
4077 	kaddr = kmap(page);
4078 	nd_terminate_link(kaddr, dentry->d_inode->i_size, PAGE_SIZE - 1);
4079 	return kaddr;
4080 }
4081 
page_readlink(struct dentry * dentry,char __user * buffer,int buflen)4082 int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
4083 {
4084 	struct page *page = NULL;
4085 	char *s = page_getlink(dentry, &page);
4086 	int res = vfs_readlink(dentry,buffer,buflen,s);
4087 	if (page) {
4088 		kunmap(page);
4089 		page_cache_release(page);
4090 	}
4091 	return res;
4092 }
4093 
page_follow_link_light(struct dentry * dentry,struct nameidata * nd)4094 void *page_follow_link_light(struct dentry *dentry, struct nameidata *nd)
4095 {
4096 	struct page *page = NULL;
4097 	nd_set_link(nd, page_getlink(dentry, &page));
4098 	return page;
4099 }
4100 
page_put_link(struct dentry * dentry,struct nameidata * nd,void * cookie)4101 void page_put_link(struct dentry *dentry, struct nameidata *nd, void *cookie)
4102 {
4103 	struct page *page = cookie;
4104 
4105 	if (page) {
4106 		kunmap(page);
4107 		page_cache_release(page);
4108 	}
4109 }
4110 
4111 /*
4112  * The nofs argument instructs pagecache_write_begin to pass AOP_FLAG_NOFS
4113  */
__page_symlink(struct inode * inode,const char * symname,int len,int nofs)4114 int __page_symlink(struct inode *inode, const char *symname, int len, int nofs)
4115 {
4116 	struct address_space *mapping = inode->i_mapping;
4117 	struct page *page;
4118 	void *fsdata;
4119 	int err;
4120 	char *kaddr;
4121 	unsigned int flags = AOP_FLAG_UNINTERRUPTIBLE;
4122 	if (nofs)
4123 		flags |= AOP_FLAG_NOFS;
4124 
4125 retry:
4126 	err = pagecache_write_begin(NULL, mapping, 0, len-1,
4127 				flags, &page, &fsdata);
4128 	if (err)
4129 		goto fail;
4130 
4131 	kaddr = kmap_atomic(page);
4132 	memcpy(kaddr, symname, len-1);
4133 	kunmap_atomic(kaddr);
4134 
4135 	err = pagecache_write_end(NULL, mapping, 0, len-1, len-1,
4136 							page, fsdata);
4137 	if (err < 0)
4138 		goto fail;
4139 	if (err < len-1)
4140 		goto retry;
4141 
4142 	mark_inode_dirty(inode);
4143 	return 0;
4144 fail:
4145 	return err;
4146 }
4147 
page_symlink(struct inode * inode,const char * symname,int len)4148 int page_symlink(struct inode *inode, const char *symname, int len)
4149 {
4150 	return __page_symlink(inode, symname, len,
4151 			!(mapping_gfp_mask(inode->i_mapping) & __GFP_FS));
4152 }
4153 
4154 const struct inode_operations page_symlink_inode_operations = {
4155 	.readlink	= generic_readlink,
4156 	.follow_link	= page_follow_link_light,
4157 	.put_link	= page_put_link,
4158 };
4159 
4160 EXPORT_SYMBOL(user_path_at);
4161 EXPORT_SYMBOL(follow_down_one);
4162 EXPORT_SYMBOL(follow_down);
4163 EXPORT_SYMBOL(follow_up);
4164 EXPORT_SYMBOL(get_write_access); /* nfsd */
4165 EXPORT_SYMBOL(lock_rename);
4166 EXPORT_SYMBOL(page_follow_link_light);
4167 EXPORT_SYMBOL(page_put_link);
4168 EXPORT_SYMBOL(page_readlink);
4169 EXPORT_SYMBOL(__page_symlink);
4170 EXPORT_SYMBOL(page_symlink);
4171 EXPORT_SYMBOL(page_symlink_inode_operations);
4172 EXPORT_SYMBOL(kern_path);
4173 EXPORT_SYMBOL(vfs_path_lookup);
4174 EXPORT_SYMBOL(unlock_rename);
4175 EXPORT_SYMBOL(vfs_follow_link);
4176 EXPORT_SYMBOL(generic_permission);
4177 EXPORT_SYMBOL(vfs_readlink);
4178 EXPORT_SYMBOL(dentry_unhash);
4179 EXPORT_SYMBOL(generic_readlink);
4180