open.c 39.9 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0-only
Linus Torvalds's avatar
Linus Torvalds committed
2 3 4 5 6 7 8 9 10
/*
 *  linux/fs/open.c
 *
 *  Copyright (C) 1991, 1992  Linus Torvalds
 */

#include <linux/string.h>
#include <linux/mm.h>
#include <linux/file.h>
Al Viro's avatar
Al Viro committed
11
#include <linux/fdtable.h>
Robert Love's avatar
Robert Love committed
12
#include <linux/fsnotify.h>
Linus Torvalds's avatar
Linus Torvalds committed
13 14 15 16
#include <linux/module.h>
#include <linux/tty.h>
#include <linux/namei.h>
#include <linux/backing-dev.h>
17
#include <linux/capability.h>
18
#include <linux/securebits.h>
Linus Torvalds's avatar
Linus Torvalds committed
19 20
#include <linux/security.h>
#include <linux/mount.h>
21
#include <linux/fcntl.h>
22
#include <linux/slab.h>
23
#include <linux/uaccess.h>
Linus Torvalds's avatar
Linus Torvalds committed
24
#include <linux/fs.h>
25
#include <linux/personality.h>
Linus Torvalds's avatar
Linus Torvalds committed
26 27
#include <linux/pagemap.h>
#include <linux/syscalls.h>
28
#include <linux/rcupdate.h>
29
#include <linux/audit.h>
30
#include <linux/falloc.h>
31
#include <linux/fs_struct.h>
32
#include <linux/dnotify.h>
Al Viro's avatar
Al Viro committed
33
#include <linux/compat.h>
34
#include <linux/mnt_idmapping.h>
35
#include <linux/filelock.h>
Linus Torvalds's avatar
Linus Torvalds committed
36

37 38
#include "internal.h"

39
int do_truncate(struct mnt_idmap *idmap, struct dentry *dentry,
40
		loff_t length, unsigned int time_attrs, struct file *filp)
Linus Torvalds's avatar
Linus Torvalds committed
41
{
42
	int ret;
Linus Torvalds's avatar
Linus Torvalds committed
43 44 45 46 47 48 49
	struct iattr newattrs;

	/* Not pretty: "inode->i_size" shouldn't really be signed. But it is. */
	if (length < 0)
		return -EINVAL;

	newattrs.ia_size = length;
50
	newattrs.ia_valid = ATTR_SIZE | time_attrs;
51 52 53 54
	if (filp) {
		newattrs.ia_file = filp;
		newattrs.ia_valid |= ATTR_FILE;
	}
Linus Torvalds's avatar
Linus Torvalds committed
55

56
	/* Remove suid, sgid, and file capabilities on truncate too */
57
	ret = dentry_needs_remove_privs(idmap, dentry);
58 59
	if (ret < 0)
		return ret;
60 61
	if (ret)
		newattrs.ia_valid |= ret | ATTR_FORCE;
62

Al Viro's avatar
Al Viro committed
63
	inode_lock(dentry->d_inode);
64
	/* Note any delegations or leases have already been broken: */
65
	ret = notify_change(idmap, dentry, &newattrs, NULL);
Al Viro's avatar
Al Viro committed
66
	inode_unlock(dentry->d_inode);
67
	return ret;
Linus Torvalds's avatar
Linus Torvalds committed
68 69
}

Al Viro's avatar
Al Viro committed
70
long vfs_truncate(const struct path *path, loff_t length)
Linus Torvalds's avatar
Linus Torvalds committed
71
{
72
	struct mnt_idmap *idmap;
73
	struct inode *inode;
74
	long error;
Linus Torvalds's avatar
Linus Torvalds committed
75

76
	inode = path->dentry->d_inode;
Linus Torvalds's avatar
Linus Torvalds committed
77 78 79

	/* For directories it's -EISDIR, for other non-regulars - -EINVAL */
	if (S_ISDIR(inode->i_mode))
80
		return -EISDIR;
Linus Torvalds's avatar
Linus Torvalds committed
81
	if (!S_ISREG(inode->i_mode))
82
		return -EINVAL;
Linus Torvalds's avatar
Linus Torvalds committed
83

84
	error = mnt_want_write(path->mnt);
Linus Torvalds's avatar
Linus Torvalds committed
85
	if (error)
86
		goto out;
Linus Torvalds's avatar
Linus Torvalds committed
87

88
	idmap = mnt_idmap(path->mnt);
89
	error = inode_permission(idmap, inode, MAY_WRITE);
90 91
	if (error)
		goto mnt_drop_write_and_out;
Linus Torvalds's avatar
Linus Torvalds committed
92 93

	error = -EPERM;
94
	if (IS_APPEND(inode))
95
		goto mnt_drop_write_and_out;
Linus Torvalds's avatar
Linus Torvalds committed
96

97
	error = get_write_access(inode);
Linus Torvalds's avatar
Linus Torvalds committed
98
	if (error)
99
		goto mnt_drop_write_and_out;
Linus Torvalds's avatar
Linus Torvalds committed
100

101 102 103 104
	/*
	 * Make sure that there are no leases.  get_write_access() protects
	 * against the truncate racing with a lease-granting setlease().
	 */
105
	error = break_lease(inode, O_WRONLY);
Linus Torvalds's avatar
Linus Torvalds committed
106
	if (error)
107
		goto put_write_and_out;
Linus Torvalds's avatar
Linus Torvalds committed
108

109
	error = security_path_truncate(path);
110
	if (!error)
111
		error = do_truncate(idmap, path->dentry, length, 0, NULL);
Linus Torvalds's avatar
Linus Torvalds committed
112

113
put_write_and_out:
114
	put_write_access(inode);
115
mnt_drop_write_and_out:
116
	mnt_drop_write(path->mnt);
Linus Torvalds's avatar
Linus Torvalds committed
117 118 119
out:
	return error;
}
120 121
EXPORT_SYMBOL_GPL(vfs_truncate);

122
long do_sys_truncate(const char __user *pathname, loff_t length)
123
{
124
	unsigned int lookup_flags = LOOKUP_FOLLOW;
125 126 127 128 129 130
	struct path path;
	int error;

	if (length < 0)	/* sorry, but loff_t says... */
		return -EINVAL;

131 132
retry:
	error = user_path_at(AT_FDCWD, pathname, lookup_flags, &path);
133 134 135 136
	if (!error) {
		error = vfs_truncate(&path, length);
		path_put(&path);
	}
137 138 139 140
	if (retry_estale(error, lookup_flags)) {
		lookup_flags |= LOOKUP_REVAL;
		goto retry;
	}
141 142
	return error;
}
Linus Torvalds's avatar
Linus Torvalds committed
143

144
SYSCALL_DEFINE2(truncate, const char __user *, path, long, length)
Linus Torvalds's avatar
Linus Torvalds committed
145
{
146
	return do_sys_truncate(path, length);
Linus Torvalds's avatar
Linus Torvalds committed
147 148
}

Al Viro's avatar
Al Viro committed
149 150 151 152 153 154 155
#ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE2(truncate, const char __user *, path, compat_off_t, length)
{
	return do_sys_truncate(path, length);
}
#endif

156
long do_ftruncate(struct file *file, loff_t length, int small)
Linus Torvalds's avatar
Linus Torvalds committed
157
{
Al Viro's avatar
Al Viro committed
158
	struct inode *inode;
Linus Torvalds's avatar
Linus Torvalds committed
159 160 161 162
	struct dentry *dentry;
	int error;

	/* explicitly opened as large or we are on 64-bit box */
163
	if (file->f_flags & O_LARGEFILE)
Linus Torvalds's avatar
Linus Torvalds committed
164 165
		small = 0;

166
	dentry = file->f_path.dentry;
Linus Torvalds's avatar
Linus Torvalds committed
167
	inode = dentry->d_inode;
168 169
	if (!S_ISREG(inode->i_mode) || !(file->f_mode & FMODE_WRITE))
		return -EINVAL;
Linus Torvalds's avatar
Linus Torvalds committed
170 171 172

	/* Cannot ftruncate over 2^31 bytes without large file support */
	if (small && length > MAX_NON_LFS)
173
		return -EINVAL;
Linus Torvalds's avatar
Linus Torvalds committed
174

175
	/* Check IS_APPEND on real upper inode */
176 177
	if (IS_APPEND(file_inode(file)))
		return -EPERM;
178
	sb_start_write(inode->i_sb);
179
	error = security_file_truncate(file);
Linus Torvalds's avatar
Linus Torvalds committed
180
	if (!error)
181 182
		error = do_truncate(file_mnt_idmap(file), dentry, length,
				    ATTR_MTIME | ATTR_CTIME, file);
183
	sb_end_write(inode->i_sb);
184 185 186 187 188 189 190 191 192 193 194 195

	return error;
}

long do_sys_ftruncate(unsigned int fd, loff_t length, int small)
{
	struct fd f;
	int error;

	if (length < 0)
		return -EINVAL;
	f = fdget(fd);
196
	if (!fd_file(f))
197 198
		return -EBADF;

199
	error = do_ftruncate(fd_file(f), length, small);
200

201
	fdput(f);
Linus Torvalds's avatar
Linus Torvalds committed
202 203 204
	return error;
}

205
SYSCALL_DEFINE2(ftruncate, unsigned int, fd, off_t, length)
Linus Torvalds's avatar
Linus Torvalds committed
206
{
207
	return do_sys_ftruncate(fd, length, 1);
Linus Torvalds's avatar
Linus Torvalds committed
208 209
}

Al Viro's avatar
Al Viro committed
210
#ifdef CONFIG_COMPAT
211
COMPAT_SYSCALL_DEFINE2(ftruncate, unsigned int, fd, compat_off_t, length)
Al Viro's avatar
Al Viro committed
212 213 214 215 216
{
	return do_sys_ftruncate(fd, length, 1);
}
#endif

Linus Torvalds's avatar
Linus Torvalds committed
217 218
/* LFS versions of truncate are only needed on 32 bit machines */
#if BITS_PER_LONG == 32
219
SYSCALL_DEFINE2(truncate64, const char __user *, path, loff_t, length)
Linus Torvalds's avatar
Linus Torvalds committed
220 221 222 223
{
	return do_sys_truncate(path, length);
}

224
SYSCALL_DEFINE2(ftruncate64, unsigned int, fd, loff_t, length)
Linus Torvalds's avatar
Linus Torvalds committed
225
{
226
	return do_sys_ftruncate(fd, length, 0);
Linus Torvalds's avatar
Linus Torvalds committed
227
}
228
#endif /* BITS_PER_LONG == 32 */
Linus Torvalds's avatar
Linus Torvalds committed
229

230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
#if defined(CONFIG_COMPAT) && defined(__ARCH_WANT_COMPAT_TRUNCATE64)
COMPAT_SYSCALL_DEFINE3(truncate64, const char __user *, pathname,
		       compat_arg_u64_dual(length))
{
	return ksys_truncate(pathname, compat_arg_u64_glue(length));
}
#endif

#if defined(CONFIG_COMPAT) && defined(__ARCH_WANT_COMPAT_FTRUNCATE64)
COMPAT_SYSCALL_DEFINE3(ftruncate64, unsigned int, fd,
		       compat_arg_u64_dual(length))
{
	return ksys_ftruncate(fd, compat_arg_u64_glue(length));
}
#endif
245

246
int vfs_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
247
{
Al Viro's avatar
Al Viro committed
248
	struct inode *inode = file_inode(file);
249
	long ret;
250
	loff_t sum;
251 252

	if (offset < 0 || len <= 0)
253
		return -EINVAL;
254

255
	if (mode & ~(FALLOC_FL_MODE_MASK | FALLOC_FL_KEEP_SIZE))
256 257
		return -EOPNOTSUPP;

258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
	/*
	 * Modes are exclusive, even if that is not obvious from the encoding
	 * as bit masks and the mix with the flag in the same namespace.
	 *
	 * To make things even more complicated, FALLOC_FL_ALLOCATE_RANGE is
	 * encoded as no bit set.
	 */
	switch (mode & FALLOC_FL_MODE_MASK) {
	case FALLOC_FL_ALLOCATE_RANGE:
	case FALLOC_FL_UNSHARE_RANGE:
	case FALLOC_FL_ZERO_RANGE:
		break;
	case FALLOC_FL_PUNCH_HOLE:
		if (!(mode & FALLOC_FL_KEEP_SIZE))
			return -EOPNOTSUPP;
		break;
	case FALLOC_FL_COLLAPSE_RANGE:
	case FALLOC_FL_INSERT_RANGE:
		if (mode & FALLOC_FL_KEEP_SIZE)
			return -EOPNOTSUPP;
		break;
	default:
280
		return -EOPNOTSUPP;
281
	}
282

283
	if (!(file->f_mode & FMODE_WRITE))
284
		return -EBADF;
285

286
	/*
287
	 * On append-only files only space preallocation is supported.
288
	 */
289
	if ((mode & ~FALLOC_FL_KEEP_SIZE) && IS_APPEND(inode))
290 291 292 293 294
		return -EPERM;

	if (IS_IMMUTABLE(inode))
		return -EPERM;

295
	/*
296
	 * We cannot allow any fallocate operation on an active swapfile
297 298
	 */
	if (IS_SWAPFILE(inode))
299
		return -ETXTBSY;
300

301 302 303 304 305 306
	/*
	 * Revalidate the write permissions, in case security policy has
	 * changed since the files were opened.
	 */
	ret = security_file_permission(file, MAY_WRITE);
	if (ret)
307
		return ret;
308

309 310 311 312
	ret = fsnotify_file_area_perm(file, MAY_WRITE, &offset, len);
	if (ret)
		return ret;

313
	if (S_ISFIFO(inode->i_mode))
314
		return -ESPIPE;
315

316 317 318 319
	if (S_ISDIR(inode->i_mode))
		return -EISDIR;

	if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))
320
		return -ENODEV;
321

322 323 324 325 326
	/* Check for wraparound */
	if (check_add_overflow(offset, len, &sum))
		return -EFBIG;

	if (sum > inode->i_sb->s_maxbytes)
327
		return -EFBIG;
328

329
	if (!file->f_op->fallocate)
330
		return -EOPNOTSUPP;
331

332
	file_start_write(file);
333
	ret = file->f_op->fallocate(file, mode, offset, len);
334 335 336 337 338 339 340 341 342 343 344

	/*
	 * Create inotify and fanotify events.
	 *
	 * To keep the logic simple always create events if fallocate succeeds.
	 * This implies that events are even created if the file size remains
	 * unchanged, e.g. when using flag FALLOC_FL_KEEP_SIZE.
	 */
	if (ret == 0)
		fsnotify_modify(file);

345
	file_end_write(file);
346
	return ret;
347
}
348
EXPORT_SYMBOL_GPL(vfs_fallocate);
349

350
int ksys_fallocate(int fd, int mode, loff_t offset, loff_t len)
351
{
352
	struct fd f = fdget(fd);
353 354
	int error = -EBADF;

355 356
	if (fd_file(f)) {
		error = vfs_fallocate(fd_file(f), mode, offset, len);
357
		fdput(f);
358 359
	}
	return error;
360
}
361

362 363 364 365 366
SYSCALL_DEFINE4(fallocate, int, fd, int, mode, loff_t, offset, loff_t, len)
{
	return ksys_fallocate(fd, mode, offset, len);
}

367 368 369 370 371 372 373 374 375
#if defined(CONFIG_COMPAT) && defined(__ARCH_WANT_COMPAT_FALLOCATE)
COMPAT_SYSCALL_DEFINE6(fallocate, int, fd, int, mode, compat_arg_u64_dual(offset),
		       compat_arg_u64_dual(len))
{
	return ksys_fallocate(fd, mode, compat_arg_u64_glue(offset),
			      compat_arg_u64_glue(len));
}
#endif

Linus Torvalds's avatar
Linus Torvalds committed
376 377 378 379
/*
 * access() needs to use the real uid/gid, not the effective uid/gid.
 * We do this by temporarily clearing all FS-related capabilities and
 * switching the fsuid/fsgid around to the real ones.
380 381 382
 *
 * Creating new credentials is expensive, so we try to skip doing it,
 * which we can if the result would match what we already got.
Linus Torvalds's avatar
Linus Torvalds committed
383
 */
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
static bool access_need_override_creds(int flags)
{
	const struct cred *cred;

	if (flags & AT_EACCESS)
		return false;

	cred = current_cred();
	if (!uid_eq(cred->fsuid, cred->uid) ||
	    !gid_eq(cred->fsgid, cred->gid))
		return true;

	if (!issecure(SECURE_NO_SETUID_FIXUP)) {
		kuid_t root_uid = make_kuid(cred->user_ns, 0);
		if (!uid_eq(cred->uid, root_uid)) {
			if (!cap_isclear(cred->cap_effective))
				return true;
		} else {
			if (!cap_isidentical(cred->cap_effective,
			    cred->cap_permitted))
				return true;
		}
	}

	return false;
}

411
static const struct cred *access_override_creds(void)
Linus Torvalds's avatar
Linus Torvalds committed
412
{
413 414
	const struct cred *old_cred;
	struct cred *override_cred;
Linus Torvalds's avatar
Linus Torvalds committed
415

416 417
	override_cred = prepare_creds();
	if (!override_cred)
418
		return NULL;
Linus Torvalds's avatar
Linus Torvalds committed
419

420 421 422 423 424 425
	/*
	 * XXX access_need_override_creds performs checks in hopes of skipping
	 * this work. Make sure it stays in sync if making any changes in this
	 * routine.
	 */

426 427
	override_cred->fsuid = override_cred->uid;
	override_cred->fsgid = override_cred->gid;
Linus Torvalds's avatar
Linus Torvalds committed
428

429
	if (!issecure(SECURE_NO_SETUID_FIXUP)) {
David Howells's avatar
David Howells committed
430
		/* Clear the capabilities if we switch to a non-root user */
431 432
		kuid_t root_uid = make_kuid(override_cred->user_ns, 0);
		if (!uid_eq(override_cred->uid, root_uid))
433
			cap_clear(override_cred->cap_effective);
434
		else
435 436
			override_cred->cap_effective =
				override_cred->cap_permitted;
437
	}
Linus Torvalds's avatar
Linus Torvalds committed
438

439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
	/*
	 * The new set of credentials can *only* be used in
	 * task-synchronous circumstances, and does not need
	 * RCU freeing, unless somebody then takes a separate
	 * reference to it.
	 *
	 * NOTE! This is _only_ true because this credential
	 * is used purely for override_creds() that installs
	 * it as the subjective cred. Other threads will be
	 * accessing ->real_cred, not the subjective cred.
	 *
	 * If somebody _does_ make a copy of this (using the
	 * 'get_current_cred()' function), that will clear the
	 * non_rcu field, because now that other user may be
	 * expecting RCU freeing. But normal thread-synchronous
454 455
	 * cred accesses will keep things non-racy to avoid RCU
	 * freeing.
456 457 458
	 */
	override_cred->non_rcu = 1;

459
	old_cred = override_creds(override_cred);
460 461 462 463 464 465 466

	/* override_cred() gets its own ref */
	put_cred(override_cred);

	return old_cred;
}

467
static long do_faccessat(int dfd, const char __user *filename, int mode, int flags)
468 469 470 471 472
{
	struct path path;
	struct inode *inode;
	int res;
	unsigned int lookup_flags = LOOKUP_FOLLOW;
473
	const struct cred *old_cred = NULL;
474 475 476 477

	if (mode & ~S_IRWXO)	/* where's F_OK, X_OK, W_OK, R_OK? */
		return -EINVAL;

478 479 480 481 482 483 484 485
	if (flags & ~(AT_EACCESS | AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH))
		return -EINVAL;

	if (flags & AT_SYMLINK_NOFOLLOW)
		lookup_flags &= ~LOOKUP_FOLLOW;
	if (flags & AT_EMPTY_PATH)
		lookup_flags |= LOOKUP_EMPTY;

486
	if (access_need_override_creds(flags)) {
487 488 489 490
		old_cred = access_override_creds();
		if (!old_cred)
			return -ENOMEM;
	}
491

492 493
retry:
	res = user_path_at(dfd, filename, lookup_flags, &path);
494 495 496
	if (res)
		goto out;

497
	inode = d_backing_inode(path.dentry);
498 499

	if ((mode & MAY_EXEC) && S_ISREG(inode->i_mode)) {
500 501 502 503 504
		/*
		 * MAY_EXEC on regular files is denied if the fs is mounted
		 * with the "noexec" flag.
		 */
		res = -EACCES;
505
		if (path_noexec(&path))
506 507 508
			goto out_path_release;
	}

509
	res = inode_permission(mnt_idmap(path.mnt), inode, mode | MAY_ACCESS);
510
	/* SuS v2 requires we report a read only fs too */
511
	if (res || !(mode & S_IWOTH) || special_file(inode->i_mode))
512
		goto out_path_release;
513 514 515 516 517 518 519 520 521 522
	/*
	 * This is a rare case where using __mnt_is_readonly()
	 * is OK without a mnt_want/drop_write() pair.  Since
	 * no actual write to the fs is performed here, we do
	 * not need to telegraph to that to anyone.
	 *
	 * By doing this, we accept that this access is
	 * inherently racy and know that the fs may change
	 * state before we even see this result.
	 */
523
	if (__mnt_is_readonly(path.mnt))
524
		res = -EROFS;
Linus Torvalds's avatar
Linus Torvalds committed
525

526
out_path_release:
527
	path_put(&path);
528 529 530 531
	if (retry_estale(res, lookup_flags)) {
		lookup_flags |= LOOKUP_REVAL;
		goto retry;
	}
532
out:
533 534 535
	if (old_cred)
		revert_creds(old_cred);

Linus Torvalds's avatar
Linus Torvalds committed
536 537 538
	return res;
}

539 540
SYSCALL_DEFINE3(faccessat, int, dfd, const char __user *, filename, int, mode)
{
541 542 543 544 545 546 547
	return do_faccessat(dfd, filename, mode, 0);
}

SYSCALL_DEFINE4(faccessat2, int, dfd, const char __user *, filename, int, mode,
		int, flags)
{
	return do_faccessat(dfd, filename, mode, flags);
548 549
}

550
SYSCALL_DEFINE2(access, const char __user *, filename, int, mode)
551
{
552
	return do_faccessat(AT_FDCWD, filename, mode, 0);
553 554
}

555
SYSCALL_DEFINE1(chdir, const char __user *, filename)
Linus Torvalds's avatar
Linus Torvalds committed
556
{
557
	struct path path;
Linus Torvalds's avatar
Linus Torvalds committed
558
	int error;
559 560 561
	unsigned int lookup_flags = LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
retry:
	error = user_path_at(AT_FDCWD, filename, lookup_flags, &path);
Linus Torvalds's avatar
Linus Torvalds committed
562 563 564
	if (error)
		goto out;

565
	error = path_permission(&path, MAY_EXEC | MAY_CHDIR);
Linus Torvalds's avatar
Linus Torvalds committed
566 567 568
	if (error)
		goto dput_and_out;

569
	set_fs_pwd(current->fs, &path);
Linus Torvalds's avatar
Linus Torvalds committed
570 571

dput_and_out:
572
	path_put(&path);
573 574 575 576
	if (retry_estale(error, lookup_flags)) {
		lookup_flags |= LOOKUP_REVAL;
		goto retry;
	}
Linus Torvalds's avatar
Linus Torvalds committed
577 578 579 580
out:
	return error;
}

581
SYSCALL_DEFINE1(fchdir, unsigned int, fd)
Linus Torvalds's avatar
Linus Torvalds committed
582
{
583
	struct fd f = fdget_raw(fd);
584
	int error;
Linus Torvalds's avatar
Linus Torvalds committed
585 586

	error = -EBADF;
587
	if (!fd_file(f))
Linus Torvalds's avatar
Linus Torvalds committed
588 589 590
		goto out;

	error = -ENOTDIR;
591
	if (!d_can_lookup(fd_file(f)->f_path.dentry))
Linus Torvalds's avatar
Linus Torvalds committed
592 593
		goto out_putf;

594
	error = file_permission(fd_file(f), MAY_EXEC | MAY_CHDIR);
Linus Torvalds's avatar
Linus Torvalds committed
595
	if (!error)
596
		set_fs_pwd(current->fs, &fd_file(f)->f_path);
Linus Torvalds's avatar
Linus Torvalds committed
597
out_putf:
598
	fdput(f);
Linus Torvalds's avatar
Linus Torvalds committed
599 600 601 602
out:
	return error;
}

603
SYSCALL_DEFINE1(chroot, const char __user *, filename)
Linus Torvalds's avatar
Linus Torvalds committed
604
{
605
	struct path path;
Linus Torvalds's avatar
Linus Torvalds committed
606
	int error;
607 608 609
	unsigned int lookup_flags = LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
retry:
	error = user_path_at(AT_FDCWD, filename, lookup_flags, &path);
Linus Torvalds's avatar
Linus Torvalds committed
610 611 612
	if (error)
		goto out;

613
	error = path_permission(&path, MAY_EXEC | MAY_CHDIR);
Linus Torvalds's avatar
Linus Torvalds committed
614 615 616 617
	if (error)
		goto dput_and_out;

	error = -EPERM;
618
	if (!ns_capable(current_user_ns(), CAP_SYS_CHROOT))
Linus Torvalds's avatar
Linus Torvalds committed
619
		goto dput_and_out;
620 621 622
	error = security_path_chroot(&path);
	if (error)
		goto dput_and_out;
Linus Torvalds's avatar
Linus Torvalds committed
623

624
	set_fs_root(current->fs, &path);
Linus Torvalds's avatar
Linus Torvalds committed
625 626
	error = 0;
dput_and_out:
627
	path_put(&path);
628 629 630 631
	if (retry_estale(error, lookup_flags)) {
		lookup_flags |= LOOKUP_REVAL;
		goto retry;
	}
Linus Torvalds's avatar
Linus Torvalds committed
632 633 634 635
out:
	return error;
}

636
int chmod_common(const struct path *path, umode_t mode)
Linus Torvalds's avatar
Linus Torvalds committed
637
{
638
	struct inode *inode = path->dentry->d_inode;
639
	struct inode *delegated_inode = NULL;
Linus Torvalds's avatar
Linus Torvalds committed
640
	struct iattr newattrs;
641
	int error;
Linus Torvalds's avatar
Linus Torvalds committed
642

643 644 645
	error = mnt_want_write(path->mnt);
	if (error)
		return error;
646
retry_deleg:
Al Viro's avatar
Al Viro committed
647
	inode_lock(inode);
648
	error = security_path_chmod(path, mode);
649
	if (error)
650
		goto out_unlock;
Linus Torvalds's avatar
Linus Torvalds committed
651 652
	newattrs.ia_mode = (mode & S_IALLUGO) | (inode->i_mode & ~S_IALLUGO);
	newattrs.ia_valid = ATTR_MODE | ATTR_CTIME;
653
	error = notify_change(mnt_idmap(path->mnt), path->dentry,
654
			      &newattrs, &delegated_inode);
655
out_unlock:
Al Viro's avatar
Al Viro committed
656
	inode_unlock(inode);
657 658 659 660 661
	if (delegated_inode) {
		error = break_deleg_wait(&delegated_inode);
		if (!error)
			goto retry_deleg;
	}
662 663 664 665
	mnt_drop_write(path->mnt);
	return error;
}

666 667 668 669 670 671
int vfs_fchmod(struct file *file, umode_t mode)
{
	audit_file(file);
	return chmod_common(&file->f_path, mode);
}

Christoph Hellwig's avatar
Christoph Hellwig committed
672
SYSCALL_DEFINE2(fchmod, unsigned int, fd, umode_t, mode)
673
{
Al Viro's avatar
Al Viro committed
674
	struct fd f = fdget(fd);
675 676
	int err = -EBADF;

677 678
	if (fd_file(f)) {
		err = vfs_fchmod(fd_file(f), mode);
Al Viro's avatar
Al Viro committed
679
		fdput(f);
680
	}
Linus Torvalds's avatar
Linus Torvalds committed
681 682 683
	return err;
}

Alexey Gladkov's avatar
Alexey Gladkov committed
684 685
static int do_fchmodat(int dfd, const char __user *filename, umode_t mode,
		       unsigned int flags)
Linus Torvalds's avatar
Linus Torvalds committed
686
{
687
	struct path path;
Linus Torvalds's avatar
Linus Torvalds committed
688
	int error;
Alexey Gladkov's avatar
Alexey Gladkov committed
689 690
	unsigned int lookup_flags;

691
	if (unlikely(flags & ~(AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH)))
Alexey Gladkov's avatar
Alexey Gladkov committed
692 693 694
		return -EINVAL;

	lookup_flags = (flags & AT_SYMLINK_NOFOLLOW) ? 0 : LOOKUP_FOLLOW;
695 696
	if (flags & AT_EMPTY_PATH)
		lookup_flags |= LOOKUP_EMPTY;
Alexey Gladkov's avatar
Alexey Gladkov committed
697

698 699
retry:
	error = user_path_at(dfd, filename, lookup_flags, &path);
700 701 702
	if (!error) {
		error = chmod_common(&path, mode);
		path_put(&path);
703 704 705 706
		if (retry_estale(error, lookup_flags)) {
			lookup_flags |= LOOKUP_REVAL;
			goto retry;
		}
707
	}
Linus Torvalds's avatar
Linus Torvalds committed
708 709 710
	return error;
}

Alexey Gladkov's avatar
Alexey Gladkov committed
711 712 713 714 715 716
SYSCALL_DEFINE4(fchmodat2, int, dfd, const char __user *, filename,
		umode_t, mode, unsigned int, flags)
{
	return do_fchmodat(dfd, filename, mode, flags);
}

717 718 719
SYSCALL_DEFINE3(fchmodat, int, dfd, const char __user *, filename,
		umode_t, mode)
{
Alexey Gladkov's avatar
Alexey Gladkov committed
720
	return do_fchmodat(dfd, filename, mode, 0);
721 722
}

723
SYSCALL_DEFINE2(chmod, const char __user *, filename, umode_t, mode)
724
{
Alexey Gladkov's avatar
Alexey Gladkov committed
725
	return do_fchmodat(AT_FDCWD, filename, mode, 0);
726 727
}

728
/*
729 730 731 732 733 734 735 736 737 738 739 740 741 742
 * Check whether @kuid is valid and if so generate and set vfsuid_t in
 * ia_vfsuid.
 *
 * Return: true if @kuid is valid, false if not.
 */
static inline bool setattr_vfsuid(struct iattr *attr, kuid_t kuid)
{
	if (!uid_valid(kuid))
		return false;
	attr->ia_valid |= ATTR_UID;
	attr->ia_vfsuid = VFSUIDT_INIT(kuid);
	return true;
}

743
/*
744 745 746 747 748 749 750 751 752 753 754 755 756 757
 * Check whether @kgid is valid and if so generate and set vfsgid_t in
 * ia_vfsgid.
 *
 * Return: true if @kgid is valid, false if not.
 */
static inline bool setattr_vfsgid(struct iattr *attr, kgid_t kgid)
{
	if (!gid_valid(kgid))
		return false;
	attr->ia_valid |= ATTR_GID;
	attr->ia_vfsgid = VFSGIDT_INIT(kgid);
	return true;
}

758
int chown_common(const struct path *path, uid_t user, gid_t group)
Linus Torvalds's avatar
Linus Torvalds committed
759
{
760
	struct mnt_idmap *idmap;
761
	struct user_namespace *fs_userns;
762
	struct inode *inode = path->dentry->d_inode;
763
	struct inode *delegated_inode = NULL;
Linus Torvalds's avatar
Linus Torvalds committed
764 765
	int error;
	struct iattr newattrs;
766 767 768 769 770
	kuid_t uid;
	kgid_t gid;

	uid = make_kuid(current_user_ns(), user);
	gid = make_kgid(current_user_ns(), group);
Linus Torvalds's avatar
Linus Torvalds committed
771

772
	idmap = mnt_idmap(path->mnt);
773
	fs_userns = i_user_ns(inode);
774

775
retry_deleg:
776 777
	newattrs.ia_vfsuid = INVALID_VFSUID;
	newattrs.ia_vfsgid = INVALID_VFSGID;
Linus Torvalds's avatar
Linus Torvalds committed
778
	newattrs.ia_valid =  ATTR_CTIME;
779 780 781 782
	if ((user != (uid_t)-1) && !setattr_vfsuid(&newattrs, uid))
		return -EINVAL;
	if ((group != (gid_t)-1) && !setattr_vfsgid(&newattrs, gid))
		return -EINVAL;
Al Viro's avatar
Al Viro committed
783
	inode_lock(inode);
784 785
	if (!S_ISDIR(inode->i_mode))
		newattrs.ia_valid |= ATTR_KILL_SUID | ATTR_KILL_PRIV |
786
				     setattr_should_drop_sgid(idmap, inode);
787 788 789
	/* Continue to send actual fs values, not the mount values. */
	error = security_path_chown(
		path,
790 791
		from_vfsuid(idmap, fs_userns, newattrs.ia_vfsuid),
		from_vfsgid(idmap, fs_userns, newattrs.ia_vfsgid));
792
	if (!error)
793
		error = notify_change(idmap, path->dentry, &newattrs,
794
				      &delegated_inode);
Al Viro's avatar
Al Viro committed
795
	inode_unlock(inode);
796 797 798 799 800
	if (delegated_inode) {
		error = break_deleg_wait(&delegated_inode);
		if (!error)
			goto retry_deleg;
	}
Linus Torvalds's avatar
Linus Torvalds committed
801 802 803
	return error;
}

804 805
int do_fchownat(int dfd, const char __user *filename, uid_t user, gid_t group,
		int flag)
806
{
807
	struct path path;
808
	int error = -EINVAL;
809
	int lookup_flags;
810

811
	if ((flag & ~(AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH)) != 0)
812 813
		goto out;

814 815 816
	lookup_flags = (flag & AT_SYMLINK_NOFOLLOW) ? 0 : LOOKUP_FOLLOW;
	if (flag & AT_EMPTY_PATH)
		lookup_flags |= LOOKUP_EMPTY;
817
retry:
818
	error = user_path_at(dfd, filename, lookup_flags, &path);
819 820
	if (error)
		goto out;
821
	error = mnt_want_write(path.mnt);
822 823
	if (error)
		goto out_release;
824
	error = chown_common(&path, user, group);
825
	mnt_drop_write(path.mnt);
826
out_release:
827
	path_put(&path);
828 829 830 831
	if (retry_estale(error, lookup_flags)) {
		lookup_flags |= LOOKUP_REVAL;
		goto retry;
	}
832 833 834 835
out:
	return error;
}

836 837 838 839 840 841
SYSCALL_DEFINE5(fchownat, int, dfd, const char __user *, filename, uid_t, user,
		gid_t, group, int, flag)
{
	return do_fchownat(dfd, filename, user, group, flag);
}

842
SYSCALL_DEFINE3(chown, const char __user *, filename, uid_t, user, gid_t, group)
Linus Torvalds's avatar
Linus Torvalds committed
843
{
844
	return do_fchownat(AT_FDCWD, filename, user, group, 0);
845
}
Linus Torvalds's avatar
Linus Torvalds committed
846

847 848
SYSCALL_DEFINE3(lchown, const char __user *, filename, uid_t, user, gid_t, group)
{
849 850
	return do_fchownat(AT_FDCWD, filename, user, group,
			   AT_SYMLINK_NOFOLLOW);
Linus Torvalds's avatar
Linus Torvalds committed
851 852
}

853 854 855 856 857 858 859 860 861 862 863 864 865
int vfs_fchown(struct file *file, uid_t user, gid_t group)
{
	int error;

	error = mnt_want_write_file(file);
	if (error)
		return error;
	audit_file(file);
	error = chown_common(&file->f_path, user, group);
	mnt_drop_write_file(file);
	return error;
}

866
int ksys_fchown(unsigned int fd, uid_t user, gid_t group)
Linus Torvalds's avatar
Linus Torvalds committed
867
{
868
	struct fd f = fdget(fd);
Linus Torvalds's avatar
Linus Torvalds committed
869 870
	int error = -EBADF;

871 872
	if (fd_file(f)) {
		error = vfs_fchown(fd_file(f), user, group);
873 874
		fdput(f);
	}
Linus Torvalds's avatar
Linus Torvalds committed
875 876 877
	return error;
}

878 879 880 881 882
SYSCALL_DEFINE3(fchown, unsigned int, fd, uid_t, user, gid_t, group)
{
	return ksys_fchown(fd, user, group);
}

883 884 885 886 887 888 889 890 891 892 893
static inline int file_get_write_access(struct file *f)
{
	int error;

	error = get_write_access(f->f_inode);
	if (unlikely(error))
		return error;
	error = mnt_get_write_access(f->f_path.mnt);
	if (unlikely(error))
		goto cleanup_inode;
	if (unlikely(f->f_mode & FMODE_BACKING)) {
894
		error = mnt_get_write_access(backing_file_user_path(f)->mnt);
895 896 897 898 899 900 901 902 903 904 905 906
		if (unlikely(error))
			goto cleanup_mnt;
	}
	return 0;

cleanup_mnt:
	mnt_put_write_access(f->f_path.mnt);
cleanup_inode:
	put_write_access(f->f_inode);
	return error;
}

907
static int do_dentry_open(struct file *f,
908
			  int (*open)(struct inode *, struct file *))
Linus Torvalds's avatar
Linus Torvalds committed
909
{
910
	static const struct file_operations empty_fops = {};
911
	struct inode *inode = f->f_path.dentry->d_inode;
Linus Torvalds's avatar
Linus Torvalds committed
912 913
	int error;

914
	path_get(&f->f_path);
915
	f->f_inode = inode;
Linus Torvalds's avatar
Linus Torvalds committed
916
	f->f_mapping = inode->i_mapping;
917
	f->f_wb_err = filemap_sample_wb_err(f->f_mapping);
918
	f->f_sb_err = file_sample_sb_err(f);
919

Al Viro's avatar
Al Viro committed
920
	if (unlikely(f->f_flags & O_PATH)) {
Al Viro's avatar
Al Viro committed
921
		f->f_mode = FMODE_PATH | FMODE_OPENED;
922
		f->f_op = &empty_fops;
923
		return 0;
924 925
	}

926 927 928
	if ((f->f_mode & (FMODE_READ | FMODE_WRITE)) == FMODE_READ) {
		i_readcount_inc(inode);
	} else if (f->f_mode & FMODE_WRITE && !special_file(inode->i_mode)) {
929
		error = file_get_write_access(f);
Al Viro's avatar
Al Viro committed
930
		if (unlikely(error))
Linus Torvalds's avatar
Linus Torvalds committed
931
			goto cleanup_file;
932
		f->f_mode |= FMODE_WRITER;
Linus Torvalds's avatar
Linus Torvalds committed
933 934
	}

935 936 937 938
	/* POSIX.1-2008/SUSv4 Section XSI 2.9.7 */
	if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode))
		f->f_mode |= FMODE_ATOMIC_POS;

939
	f->f_op = fops_get(inode->i_fop);
940
	if (WARN_ON(!f->f_op)) {
Al Viro's avatar
Al Viro committed
941 942 943
		error = -ENODEV;
		goto cleanup_all;
	}
944

945
	error = security_file_open(f);
946 947 948
	if (error)
		goto cleanup_all;

Jeff Layton's avatar
Jeff Layton committed
949
	error = break_lease(file_inode(f), f->f_flags);
950 951 952
	if (error)
		goto cleanup_all;

953 954
	/* normally all 3 are set; ->open() can clear them if needed */
	f->f_mode |= FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE;
Al Viro's avatar
Al Viro committed
955
	if (!open)
956 957 958
		open = f->f_op->open;
	if (open) {
		error = open(inode, f);
Linus Torvalds's avatar
Linus Torvalds committed
959 960 961
		if (error)
			goto cleanup_all;
	}
Al Viro's avatar
Al Viro committed
962
	f->f_mode |= FMODE_OPENED;
963
	if ((f->f_mode & FMODE_READ) &&
964
	     likely(f->f_op->read || f->f_op->read_iter))
965
		f->f_mode |= FMODE_CAN_READ;
966
	if ((f->f_mode & FMODE_WRITE) &&
967
	     likely(f->f_op->write || f->f_op->write_iter))
968
		f->f_mode |= FMODE_CAN_WRITE;
969 970
	if ((f->f_mode & FMODE_LSEEK) && !f->f_op->llseek)
		f->f_mode &= ~FMODE_LSEEK;
971 972
	if (f->f_mapping->a_ops && f->f_mapping->a_ops->direct_IO)
		f->f_mode |= FMODE_CAN_ODIRECT;
973

Linus Torvalds's avatar
Linus Torvalds committed
974
	f->f_flags &= ~(O_CREAT | O_EXCL | O_NOCTTY | O_TRUNC);
975
	f->f_iocb_flags = iocb_flags(f);
Linus Torvalds's avatar
Linus Torvalds committed
976 977

	file_ra_state_init(&f->f_ra, f->f_mapping->host->i_mapping);
978

979 980
	if ((f->f_flags & O_DIRECT) && !(f->f_mode & FMODE_CAN_ODIRECT))
		return -EINVAL;
981 982 983 984 985

	/*
	 * XXX: Huge page cache doesn't support writing yet. Drop all page
	 * cache for this file before processing writes.
	 */
986 987
	if (f->f_mode & FMODE_WRITE) {
		/*
988 989 990 991
		 * Depends on full fence from get_write_access() to synchronize
		 * against collapse_file() regarding i_writecount and nr_thps
		 * updates. Ensures subsequent insertion of THPs into the page
		 * cache will fail.
992
		 */
993
		if (filemap_nr_thps(inode->i_mapping)) {
994 995
			struct address_space *mapping = inode->i_mapping;

996
			filemap_invalidate_lock(inode->i_mapping);
997 998 999 1000 1001 1002 1003 1004
			/*
			 * unmap_mapping_range just need to be called once
			 * here, because the private pages is not need to be
			 * unmapped mapping (e.g. data segment of dynamic
			 * shared libraries here).
			 */
			unmap_mapping_range(mapping, 0, 0, 0);
			truncate_inode_pages(mapping, 0);
1005 1006
			filemap_invalidate_unlock(inode->i_mapping);
		}
1007
	}
1008

1009
	return 0;
Linus Torvalds's avatar
Linus Torvalds committed
1010 1011

cleanup_all:
1012 1013
	if (WARN_ON_ONCE(error > 0))
		error = -EINVAL;
Linus Torvalds's avatar
Linus Torvalds committed
1014
	fops_put(f->f_op);
1015
	put_file_access(f);
Linus Torvalds's avatar
Linus Torvalds committed
1016
cleanup_file:
1017 1018 1019
	path_put(&f->f_path);
	f->f_path.mnt = NULL;
	f->f_path.dentry = NULL;
1020
	f->f_inode = NULL;
1021
	return error;
Linus Torvalds's avatar
Linus Torvalds committed
1022 1023
}

1024 1025
/**
 * finish_open - finish opening a file
1026
 * @file: file pointer
1027 1028 1029 1030 1031 1032 1033
 * @dentry: pointer to dentry
 * @open: open callback
 *
 * This can be used to finish opening a file passed to i_op->atomic_open().
 *
 * If the open callback is set to NULL, then the standard f_op->open()
 * filesystem callback is substituted.
1034 1035 1036 1037 1038 1039
 *
 * NB: the dentry reference is _not_ consumed.  If, for example, the dentry is
 * the return value of d_splice_alias(), then the caller needs to perform dput()
 * on it after finish_open().
 *
 * Returns zero on success or -errno if the open failed.
1040
 */
Al Viro's avatar
Al Viro committed
1041
int finish_open(struct file *file, struct dentry *dentry,
1042
		int (*open)(struct inode *, struct file *))
1043
{
1044
	BUG_ON(file->f_mode & FMODE_OPENED); /* once it's opened, it's opened */
1045

1046
	file->f_path.dentry = dentry;
1047
	return do_dentry_open(file, open);
1048 1049 1050 1051 1052 1053
}
EXPORT_SYMBOL(finish_open);

/**
 * finish_no_open - finish ->atomic_open() without opening the file
 *
1054
 * @file: file pointer
1055 1056 1057
 * @dentry: dentry or NULL (as returned from ->lookup())
 *
 * This can be used to set the result of a successful lookup in ->atomic_open().
1058 1059 1060 1061
 *
 * NB: unlike finish_open() this function does consume the dentry reference and
 * the caller need not dput() it.
 *
1062
 * Returns "0" which must be the return value of ->atomic_open() after having
1063
 * called this function.
1064
 */
Al Viro's avatar
Al Viro committed
1065
int finish_no_open(struct file *file, struct dentry *dentry)
1066
{
Al Viro's avatar
Al Viro committed
1067
	file->f_path.dentry = dentry;
1068
	return 0;
1069 1070 1071
}
EXPORT_SYMBOL(finish_no_open);

1072 1073 1074 1075 1076 1077
char *file_path(struct file *filp, char *buf, int buflen)
{
	return d_path(&filp->f_path, buf, buflen);
}
EXPORT_SYMBOL(file_path);

1078 1079 1080 1081 1082
/**
 * vfs_open - open the file at the given path
 * @path: path to open
 * @file: newly allocated file with f_flag initialized
 */
1083
int vfs_open(const struct path *path, struct file *file)
1084
{
1085 1086
	int ret;

1087
	file->f_path = *path;
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
	ret = do_dentry_open(file, NULL);
	if (!ret) {
		/*
		 * Once we return a file with FMODE_OPENED, __fput() will call
		 * fsnotify_close(), so we need fsnotify_open() here for
		 * symmetry.
		 */
		fsnotify_open(file);
	}
	return ret;
1098 1099
}

1100
struct file *dentry_open(const struct path *path, int flags,
1101
			 const struct cred *cred)
1102 1103 1104 1105
{
	int error;
	struct file *f;

1106
	/* We must always pass in a valid mount pointer. */
1107
	BUG_ON(!path->mnt);
1108

1109
	f = alloc_empty_file(flags, cred);
1110
	if (!IS_ERR(f)) {
1111
		error = vfs_open(path, f);
Al Viro's avatar
Al Viro committed
1112 1113
		if (error) {
			fput(f);
1114 1115
			f = ERR_PTR(error);
		}
1116 1117
	}
	return f;
1118
}
Linus Torvalds's avatar
Linus Torvalds committed
1119 1120
EXPORT_SYMBOL(dentry_open);

1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
/**
 * dentry_create - Create and open a file
 * @path: path to create
 * @flags: O_ flags
 * @mode: mode bits for new file
 * @cred: credentials to use
 *
 * Caller must hold the parent directory's lock, and have prepared
 * a negative dentry, placed in @path->dentry, for the new file.
 *
 * Caller sets @path->mnt to the vfsmount of the filesystem where
 * the new file is to be created. The parent directory and the
 * negative dentry must reside on the same filesystem instance.
 *
 * On success, returns a "struct file *". Otherwise a ERR_PTR
 * is returned.
 */
struct file *dentry_create(const struct path *path, int flags, umode_t mode,
			   const struct cred *cred)
{
	struct file *f;
	int error;

	f = alloc_empty_file(flags, cred);
	if (IS_ERR(f))
		return f;

1148
	error = vfs_create(mnt_idmap(path->mnt),
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
			   d_inode(path->dentry->d_parent),
			   path->dentry, mode, true);
	if (!error)
		error = vfs_open(path, f);

	if (unlikely(error)) {
		fput(f);
		return ERR_PTR(error);
	}
	return f;
}
EXPORT_SYMBOL(dentry_create);

1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
/**
 * kernel_file_open - open a file for kernel internal use
 * @path:	path of the file to open
 * @flags:	open flags
 * @cred:	credentials for open
 *
 * Open a file for use by in-kernel consumers. The file is not accounted
 * against nr_files and must not be installed into the file descriptor
 * table.
 *
 * Return: Opened file on success, an error pointer on failure.
 */
struct file *kernel_file_open(const struct path *path, int flags,
1175
				const struct cred *cred)
1176
{
1177 1178
	struct file *f;
	int error;
1179

1180 1181 1182 1183 1184
	f = alloc_empty_file_noaccount(flags, cred);
	if (IS_ERR(f))
		return f;

	f->f_path = *path;
1185
	error = do_dentry_open(f, NULL);
1186 1187
	if (error) {
		fput(f);
1188
		return ERR_PTR(error);
1189
	}
1190 1191

	fsnotify_open(f);
1192 1193
	return f;
}
1194 1195
EXPORT_SYMBOL_GPL(kernel_file_open);

1196 1197 1198
#define WILL_CREATE(flags)	(flags & (O_CREAT | __O_TMPFILE))
#define O_PATH_FLAGS		(O_DIRECTORY | O_NOFOLLOW | O_PATH | O_CLOEXEC)

1199
inline struct open_how build_open_how(int flags, umode_t mode)
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
{
	struct open_how how = {
		.flags = flags & VALID_OPEN_FLAGS,
		.mode = mode & S_IALLUGO,
	};

	/* O_PATH beats everything else. */
	if (how.flags & O_PATH)
		how.flags &= O_PATH_FLAGS;
	/* Modes should only be set for create-like flags. */
	if (!WILL_CREATE(how.flags))
		how.mode = 0;
	return how;
}

1215
inline int build_open_flags(const struct open_how *how, struct open_flags *op)
1216
{
1217
	u64 flags = how->flags;
1218
	u64 strip = __FMODE_NONOTIFY | O_CLOEXEC;
1219
	int lookup_flags = 0;
1220
	int acc_mode = ACC_MODE(flags);
1221

1222 1223 1224 1225 1226 1227 1228 1229 1230
	BUILD_BUG_ON_MSG(upper_32_bits(VALID_OPEN_FLAGS),
			 "struct open_flags doesn't yet handle flags > 32 bits");

	/*
	 * Strip flags that either shouldn't be set by userspace like
	 * FMODE_NONOTIFY or that aren't relevant in determining struct
	 * open_flags like O_CLOEXEC.
	 */
	flags &= ~strip;
1231

1232
	/*
1233 1234 1235
	 * Older syscalls implicitly clear all of the invalid flags or argument
	 * values before calling build_open_flags(), but openat2(2) checks all
	 * of its arguments.
1236
	 */
1237 1238 1239 1240
	if (flags & ~VALID_OPEN_FLAGS)
		return -EINVAL;
	if (how->resolve & ~VALID_RESOLVE_FLAGS)
		return -EINVAL;
1241

1242 1243 1244 1245
	/* Scoping flags are mutually exclusive. */
	if ((how->resolve & RESOLVE_BENEATH) && (how->resolve & RESOLVE_IN_ROOT))
		return -EINVAL;

1246 1247 1248 1249 1250 1251 1252 1253
	/* Deal with the mode. */
	if (WILL_CREATE(flags)) {
		if (how->mode & ~S_IALLUGO)
			return -EINVAL;
		op->mode = how->mode | S_IFREG;
	} else {
		if (how->mode != 0)
			return -EINVAL;
1254
		op->mode = 0;
1255
	}
1256 1257

	/*
1258 1259 1260
	 * Block bugs where O_DIRECTORY | O_CREAT created regular files.
	 * Note, that blocking O_DIRECTORY | O_CREAT here also protects
	 * O_TMPFILE below which requires O_DIRECTORY being raised.
1261
	 */
1262 1263 1264 1265
	if ((flags & (O_DIRECTORY | O_CREAT)) == (O_DIRECTORY | O_CREAT))
		return -EINVAL;

	/* Now handle the creative implementation of O_TMPFILE. */
Al Viro's avatar
Al Viro committed
1266
	if (flags & __O_TMPFILE) {
1267 1268 1269 1270 1271 1272
		/*
		 * In order to ensure programs get explicit errors when trying
		 * to use O_TMPFILE on old kernels we enforce that O_DIRECTORY
		 * is raised alongside __O_TMPFILE.
		 */
		if (!(flags & O_DIRECTORY))
1273
			return -EINVAL;
1274 1275
		if (!(acc_mode & MAY_WRITE))
			return -EINVAL;
1276 1277 1278 1279 1280
	}
	if (flags & O_PATH) {
		/* O_PATH only permits certain other flags to be set. */
		if (flags & ~O_PATH_FLAGS)
			return -EINVAL;
1281 1282
		acc_mode = 0;
	}
1283

1284 1285 1286 1287 1288 1289 1290 1291 1292
	/*
	 * O_SYNC is implemented as __O_SYNC|O_DSYNC.  As many places only
	 * check for O_DSYNC if the need any syncing at all we enforce it's
	 * always set instead of having to deal with possibly weird behaviour
	 * for malicious applications setting only __O_SYNC.
	 */
	if (flags & __O_SYNC)
		flags |= O_DSYNC;

1293
	op->open_flag = flags;
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305

	/* O_TRUNC implies we need access checks for write permissions */
	if (flags & O_TRUNC)
		acc_mode |= MAY_WRITE;

	/* Allow the LSM permission hook to distinguish append
	   access from general write access. */
	if (flags & O_APPEND)
		acc_mode |= MAY_APPEND;

	op->acc_mode = acc_mode;

1306 1307
	op->intent = flags & O_PATH ? 0 : LOOKUP_OPEN;

1308 1309
	if (flags & O_CREAT) {
		op->intent |= LOOKUP_CREATE;
1310
		if (flags & O_EXCL) {
1311
			op->intent |= LOOKUP_EXCL;
1312 1313
			flags |= O_NOFOLLOW;
		}
1314 1315 1316 1317 1318 1319
	}

	if (flags & O_DIRECTORY)
		lookup_flags |= LOOKUP_DIRECTORY;
	if (!(flags & O_NOFOLLOW))
		lookup_flags |= LOOKUP_FOLLOW;
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330

	if (how->resolve & RESOLVE_NO_XDEV)
		lookup_flags |= LOOKUP_NO_XDEV;
	if (how->resolve & RESOLVE_NO_MAGICLINKS)
		lookup_flags |= LOOKUP_NO_MAGICLINKS;
	if (how->resolve & RESOLVE_NO_SYMLINKS)
		lookup_flags |= LOOKUP_NO_SYMLINKS;
	if (how->resolve & RESOLVE_BENEATH)
		lookup_flags |= LOOKUP_BENEATH;
	if (how->resolve & RESOLVE_IN_ROOT)
		lookup_flags |= LOOKUP_IN_ROOT;
1331 1332
	if (how->resolve & RESOLVE_CACHED) {
		/* Don't bother even trying for create/truncate/tmpfile open */
1333
		if (flags & (O_TRUNC | O_CREAT | __O_TMPFILE))
1334 1335 1336
			return -EAGAIN;
		lookup_flags |= LOOKUP_CACHED;
	}
1337

1338 1339
	op->lookup_flags = lookup_flags;
	return 0;
1340 1341
}

1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
/**
 * file_open_name - open file and return file pointer
 *
 * @name:	struct filename containing path to open
 * @flags:	open flags as per the open(2) second argument
 * @mode:	mode for the new file if O_CREAT is set, else ignored
 *
 * This is the helper to open a file from kernelspace if you really
 * have to.  But in generally you should not do this, so please move
 * along, nothing to see here..
 */
struct file *file_open_name(struct filename *name, int flags, umode_t mode)
{
	struct open_flags op;
1356 1357 1358 1359 1360
	struct open_how how = build_open_how(flags, mode);
	int err = build_open_flags(&how, &op);
	if (err)
		return ERR_PTR(err);
	return do_filp_open(AT_FDCWD, name, &op);
1361 1362
}

1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
/**
 * filp_open - open file and return file pointer
 *
 * @filename:	path to open
 * @flags:	open flags as per the open(2) second argument
 * @mode:	mode for the new file if O_CREAT is set, else ignored
 *
 * This is the helper to open a file from kernelspace if you really
 * have to.  But in generally you should not do this, so please move
 * along, nothing to see here..
 */
1374
struct file *filp_open(const char *filename, int flags, umode_t mode)
1375
{
1376 1377
	struct filename *name = getname_kernel(filename);
	struct file *file = ERR_CAST(name);
1378

1379 1380 1381 1382 1383
	if (!IS_ERR(name)) {
		file = file_open_name(name, flags, mode);
		putname(name);
	}
	return file;
1384 1385 1386
}
EXPORT_SYMBOL(filp_open);

1387
struct file *file_open_root(const struct path *root,
1388
			    const char *filename, int flags, umode_t mode)
1389 1390
{
	struct open_flags op;
1391 1392
	struct open_how how = build_open_how(flags, mode);
	int err = build_open_flags(&how, &op);
1393 1394
	if (err)
		return ERR_PTR(err);
1395
	return do_file_open_root(root, filename, &op);
1396 1397 1398
}
EXPORT_SYMBOL(file_open_root);

1399 1400
static long do_sys_openat2(int dfd, const char __user *filename,
			   struct open_how *how)
Linus Torvalds's avatar
Linus Torvalds committed
1401
{
1402
	struct open_flags op;
1403
	int fd = build_open_flags(how, &op);
1404 1405 1406 1407 1408 1409 1410 1411 1412
	struct filename *tmp;

	if (fd)
		return fd;

	tmp = getname(filename);
	if (IS_ERR(tmp))
		return PTR_ERR(tmp);

1413
	fd = get_unused_fd_flags(how->flags);
1414 1415 1416 1417 1418 1419 1420
	if (fd >= 0) {
		struct file *f = do_filp_open(dfd, tmp, &op);
		if (IS_ERR(f)) {
			put_unused_fd(fd);
			fd = PTR_ERR(f);
		} else {
			fd_install(fd, f);
Linus Torvalds's avatar
Linus Torvalds committed
1421 1422
		}
	}
1423
	putname(tmp);
Linus Torvalds's avatar
Linus Torvalds committed
1424 1425
	return fd;
}
1426

1427
long do_sys_open(int dfd, const char __user *filename, int flags, umode_t mode)
1428
{
1429 1430 1431
	struct open_how how = build_open_how(flags, mode);
	return do_sys_openat2(dfd, filename, &how);
}
1432

1433 1434 1435

SYSCALL_DEFINE3(open, const char __user *, filename, int, flags, umode_t, mode)
{
Christoph Hellwig's avatar
Christoph Hellwig committed
1436 1437 1438
	if (force_o_largefile())
		flags |= O_LARGEFILE;
	return do_sys_open(AT_FDCWD, filename, flags, mode);
1439
}
Linus Torvalds's avatar
Linus Torvalds committed
1440

1441
SYSCALL_DEFINE4(openat, int, dfd, const char __user *, filename, int, flags,
1442
		umode_t, mode)
1443 1444 1445
{
	if (force_o_largefile())
		flags |= O_LARGEFILE;
1446
	return do_sys_open(dfd, filename, flags, mode);
1447 1448
}

1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
SYSCALL_DEFINE4(openat2, int, dfd, const char __user *, filename,
		struct open_how __user *, how, size_t, usize)
{
	int err;
	struct open_how tmp;

	BUILD_BUG_ON(sizeof(struct open_how) < OPEN_HOW_SIZE_VER0);
	BUILD_BUG_ON(sizeof(struct open_how) != OPEN_HOW_SIZE_LATEST);

	if (unlikely(usize < OPEN_HOW_SIZE_VER0))
		return -EINVAL;
1460 1461
	if (unlikely(usize > PAGE_SIZE))
		return -E2BIG;
1462 1463 1464 1465 1466

	err = copy_struct_from_user(&tmp, sizeof(tmp), how, usize);
	if (err)
		return err;

1467 1468
	audit_openat2_how(&tmp);

1469 1470 1471 1472 1473 1474 1475
	/* O_LARGEFILE is only allowed for non-O_PATH. */
	if (!(tmp.flags & O_PATH) && force_o_largefile())
		tmp.flags |= O_LARGEFILE;

	return do_sys_openat2(dfd, filename, &tmp);
}

1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
#ifdef CONFIG_COMPAT
/*
 * Exactly like sys_open(), except that it doesn't set the
 * O_LARGEFILE flag.
 */
COMPAT_SYSCALL_DEFINE3(open, const char __user *, filename, int, flags, umode_t, mode)
{
	return do_sys_open(AT_FDCWD, filename, flags, mode);
}

/*
 * Exactly like sys_openat(), except that it doesn't set the
 * O_LARGEFILE flag.
 */
COMPAT_SYSCALL_DEFINE4(openat, int, dfd, const char __user *, filename, int, flags, umode_t, mode)
{
	return do_sys_open(dfd, filename, flags, mode);
}
#endif

Linus Torvalds's avatar
Linus Torvalds committed
1496 1497 1498 1499 1500 1501
#ifndef __alpha__

/*
 * For backward compatibility?  Maybe this should be moved
 * into arch/i386 instead?
 */
1502
SYSCALL_DEFINE2(creat, const char __user *, pathname, umode_t, mode)
Linus Torvalds's avatar
Linus Torvalds committed
1503
{
Christoph Hellwig's avatar
Christoph Hellwig committed
1504
	int flags = O_CREAT | O_WRONLY | O_TRUNC;
Linus Torvalds's avatar
Linus Torvalds committed
1505

Christoph Hellwig's avatar
Christoph Hellwig committed
1506 1507 1508 1509
	if (force_o_largefile())
		flags |= O_LARGEFILE;
	return do_sys_open(AT_FDCWD, pathname, flags, mode);
}
Linus Torvalds's avatar
Linus Torvalds committed
1510 1511 1512 1513 1514 1515
#endif

/*
 * "id" is the POSIX thread ID. We use the
 * files pointer for this..
 */
1516
static int filp_flush(struct file *filp, fl_owner_t id)
Linus Torvalds's avatar
Linus Torvalds committed
1517
{
1518
	int retval = 0;
Linus Torvalds's avatar
Linus Torvalds committed
1519

1520 1521 1522
	if (CHECK_DATA_CORRUPTION(file_count(filp) == 0,
			"VFS: Close: file count is 0 (f_op=%ps)",
			filp->f_op)) {
1523
		return 0;
Linus Torvalds's avatar
Linus Torvalds committed
1524 1525
	}

Al Viro's avatar
Al Viro committed
1526
	if (filp->f_op->flush)
1527
		retval = filp->f_op->flush(filp, id);
Linus Torvalds's avatar
Linus Torvalds committed
1528

1529 1530 1531 1532
	if (likely(!(filp->f_mode & FMODE_PATH))) {
		dnotify_flush(filp, id);
		locks_remove_posix(filp, id);
	}
Linus Torvalds's avatar
Linus Torvalds committed
1533 1534 1535
	return retval;
}

1536 1537 1538 1539 1540 1541 1542 1543 1544
int filp_close(struct file *filp, fl_owner_t id)
{
	int retval;

	retval = filp_flush(filp, id);
	fput(filp);

	return retval;
}
Linus Torvalds's avatar
Linus Torvalds committed
1545 1546 1547 1548 1549 1550 1551
EXPORT_SYMBOL(filp_close);

/*
 * Careful here! We test whether the file pointer is NULL before
 * releasing the fd. This ensures that one clone task can't release
 * an fd while another clone is opening it.
 */
1552
SYSCALL_DEFINE1(close, unsigned int, fd)
Linus Torvalds's avatar
Linus Torvalds committed
1553
{
1554 1555 1556
	int retval;
	struct file *file;

1557
	file = file_close_fd(fd);
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
	if (!file)
		return -EBADF;

	retval = filp_flush(file, current->files);

	/*
	 * We're returning to user space. Don't bother
	 * with any delayed fput() cases.
	 */
	__fput_sync(file);
1568 1569 1570 1571 1572 1573 1574 1575 1576

	/* can't restart close syscall because file table entry was cleared */
	if (unlikely(retval == -ERESTARTSYS ||
		     retval == -ERESTARTNOINTR ||
		     retval == -ERESTARTNOHAND ||
		     retval == -ERESTART_RESTARTBLOCK))
		retval = -EINTR;

	return retval;
Linus Torvalds's avatar
Linus Torvalds committed
1577 1578
}

1579
/**
1580
 * sys_close_range() - Close all file descriptors in a given range.
1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
 *
 * @fd:     starting file descriptor to close
 * @max_fd: last file descriptor to close
 * @flags:  reserved for future extensions
 *
 * This closes a range of file descriptors. All file descriptors
 * from @fd up to and including @max_fd are closed.
 * Currently, errors to close a given file descriptor are ignored.
 */
SYSCALL_DEFINE3(close_range, unsigned int, fd, unsigned int, max_fd,
		unsigned int, flags)
{
1593
	return __close_range(fd, max_fd, flags);
1594 1595
}

Linus Torvalds's avatar
Linus Torvalds committed
1596 1597 1598 1599
/*
 * This routine simulates a hangup on the tty, to arrange that users
 * are given clean terminals at login time.
 */
1600
SYSCALL_DEFINE0(vhangup)
Linus Torvalds's avatar
Linus Torvalds committed
1601 1602
{
	if (capable(CAP_SYS_TTY_CONFIG)) {
Alan Cox's avatar
Alan Cox committed
1603
		tty_vhangup_self();
Linus Torvalds's avatar
Linus Torvalds committed
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
		return 0;
	}
	return -EPERM;
}

/*
 * Called when an inode is about to be open.
 * We use this to disallow opening large files on 32bit systems if
 * the caller didn't specify O_LARGEFILE.  On 64bit systems we force
 * on this flag in sys_open.
 */
int generic_file_open(struct inode * inode, struct file * filp)
{
	if (!(filp->f_flags & O_LARGEFILE) && i_size_read(inode) > MAX_NON_LFS)
1618
		return -EOVERFLOW;
Linus Torvalds's avatar
Linus Torvalds committed
1619 1620 1621 1622 1623 1624 1625
	return 0;
}

EXPORT_SYMBOL(generic_file_open);

/*
 * This is used by subsystems that don't want seekable
1626 1627 1628
 * file descriptors. The function is not supposed to ever fail, the only
 * reason it returns an 'int' and not 'void' is so that it can be plugged
 * directly into file_operations structure.
Linus Torvalds's avatar
Linus Torvalds committed
1629 1630 1631 1632 1633 1634 1635 1636
 */
int nonseekable_open(struct inode *inode, struct file *filp)
{
	filp->f_mode &= ~(FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE);
	return 0;
}

EXPORT_SYMBOL(nonseekable_open);
1637 1638 1639 1640

/*
 * stream_open is used by subsystems that want stream-like file descriptors.
 * Such file descriptors are not seekable and don't have notion of position
1641 1642 1643
 * (file.f_pos is always 0 and ppos passed to .read()/.write() is always NULL).
 * Contrary to file descriptors of other regular files, .read() and .write()
 * can run simultaneously.
1644 1645 1646 1647 1648 1649
 *
 * stream_open never fails and is marked to return int so that it could be
 * directly used as file_operations.open .
 */
int stream_open(struct inode *inode, struct file *filp)
{
1650
	filp->f_mode &= ~(FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE | FMODE_ATOMIC_POS);
1651 1652 1653 1654 1655
	filp->f_mode |= FMODE_STREAM;
	return 0;
}

EXPORT_SYMBOL(stream_open);