Merge tag 'sched_ext-for-6.12' of git://git.kernel.org/pub/scm/linux/kernel/git/tj...
[linux-2.6-block.git] / fs / open.c
CommitLineData
457c8996 1// SPDX-License-Identifier: GPL-2.0-only
1da177e4
LT
2/*
3 * linux/fs/open.c
4 *
5 * Copyright (C) 1991, 1992 Linus Torvalds
6 */
7
8#include <linux/string.h>
9#include <linux/mm.h>
1da177e4 10#include <linux/file.h>
9f3acc31 11#include <linux/fdtable.h>
0eeca283 12#include <linux/fsnotify.h>
1da177e4 13#include <linux/module.h>
1da177e4
LT
14#include <linux/tty.h>
15#include <linux/namei.h>
16#include <linux/backing-dev.h>
16f7e0fe 17#include <linux/capability.h>
086f7316 18#include <linux/securebits.h>
1da177e4
LT
19#include <linux/security.h>
20#include <linux/mount.h>
5590ff0d 21#include <linux/fcntl.h>
5a0e3ad6 22#include <linux/slab.h>
7c0f6ba6 23#include <linux/uaccess.h>
1da177e4 24#include <linux/fs.h>
ef3daeda 25#include <linux/personality.h>
1da177e4
LT
26#include <linux/pagemap.h>
27#include <linux/syscalls.h>
ab2af1f5 28#include <linux/rcupdate.h>
73241ccc 29#include <linux/audit.h>
97ac7350 30#include <linux/falloc.h>
5ad4e53b 31#include <linux/fs_struct.h>
2dfc1cae 32#include <linux/dnotify.h>
3f6d078d 33#include <linux/compat.h>
a793d79e 34#include <linux/mnt_idmapping.h>
5970e15d 35#include <linux/filelock.h>
1da177e4 36
e81e3f4d
EP
37#include "internal.h"
38
abf08576 39int do_truncate(struct mnt_idmap *idmap, struct dentry *dentry,
643fe55a 40 loff_t length, unsigned int time_attrs, struct file *filp)
1da177e4 41{
939a9421 42 int ret;
1da177e4
LT
43 struct iattr newattrs;
44
45 /* Not pretty: "inode->i_size" shouldn't really be signed. But it is. */
46 if (length < 0)
47 return -EINVAL;
48
49 newattrs.ia_size = length;
4a30131e 50 newattrs.ia_valid = ATTR_SIZE | time_attrs;
cc4e69de
MS
51 if (filp) {
52 newattrs.ia_file = filp;
53 newattrs.ia_valid |= ATTR_FILE;
54 }
1da177e4 55
45f147a1 56 /* Remove suid, sgid, and file capabilities on truncate too */
9452e93e 57 ret = dentry_needs_remove_privs(idmap, dentry);
45f147a1
JK
58 if (ret < 0)
59 return ret;
939a9421
AW
60 if (ret)
61 newattrs.ia_valid |= ret | ATTR_FORCE;
7b82dc0e 62
5955102c 63 inode_lock(dentry->d_inode);
27ac0ffe 64 /* Note any delegations or leases have already been broken: */
abf08576 65 ret = notify_change(idmap, dentry, &newattrs, NULL);
5955102c 66 inode_unlock(dentry->d_inode);
939a9421 67 return ret;
1da177e4
LT
68}
69
7df818b2 70long vfs_truncate(const struct path *path, loff_t length)
1da177e4 71{
abf08576 72 struct mnt_idmap *idmap;
2d8f3038 73 struct inode *inode;
a02de960 74 long error;
1da177e4 75
a02de960 76 inode = path->dentry->d_inode;
1da177e4
LT
77
78 /* For directories it's -EISDIR, for other non-regulars - -EINVAL */
1da177e4 79 if (S_ISDIR(inode->i_mode))
a02de960 80 return -EISDIR;
1da177e4 81 if (!S_ISREG(inode->i_mode))
a02de960 82 return -EINVAL;
1da177e4 83
a02de960 84 error = mnt_want_write(path->mnt);
1da177e4 85 if (error)
a02de960 86 goto out;
1da177e4 87
abf08576 88 idmap = mnt_idmap(path->mnt);
4609e1f1 89 error = inode_permission(idmap, inode, MAY_WRITE);
9ac9b847
DH
90 if (error)
91 goto mnt_drop_write_and_out;
1da177e4
LT
92
93 error = -EPERM;
c82e42da 94 if (IS_APPEND(inode))
9ac9b847 95 goto mnt_drop_write_and_out;
1da177e4 96
8cf9ee50 97 error = get_write_access(inode);
1da177e4 98 if (error)
9ac9b847 99 goto mnt_drop_write_and_out;
1da177e4 100
9700382c 101 /*
102 * Make sure that there are no leases. get_write_access() protects
103 * against the truncate racing with a lease-granting setlease().
104 */
8737c930 105 error = break_lease(inode, O_WRONLY);
1da177e4 106 if (error)
9700382c 107 goto put_write_and_out;
1da177e4 108
f7e33bdb 109 error = security_path_truncate(path);
907f4554 110 if (!error)
abf08576 111 error = do_truncate(idmap, path->dentry, length, 0, NULL);
1da177e4 112
9700382c 113put_write_and_out:
8cf9ee50 114 put_write_access(inode);
9ac9b847 115mnt_drop_write_and_out:
a02de960 116 mnt_drop_write(path->mnt);
1da177e4
LT
117out:
118 return error;
119}
a02de960
DH
120EXPORT_SYMBOL_GPL(vfs_truncate);
121
df260e21 122long do_sys_truncate(const char __user *pathname, loff_t length)
a02de960 123{
48f7530d 124 unsigned int lookup_flags = LOOKUP_FOLLOW;
a02de960
DH
125 struct path path;
126 int error;
127
128 if (length < 0) /* sorry, but loff_t says... */
129 return -EINVAL;
130
48f7530d
JL
131retry:
132 error = user_path_at(AT_FDCWD, pathname, lookup_flags, &path);
a02de960
DH
133 if (!error) {
134 error = vfs_truncate(&path, length);
135 path_put(&path);
136 }
48f7530d
JL
137 if (retry_estale(error, lookup_flags)) {
138 lookup_flags |= LOOKUP_REVAL;
139 goto retry;
140 }
a02de960
DH
141 return error;
142}
1da177e4 143
4fd8da8d 144SYSCALL_DEFINE2(truncate, const char __user *, path, long, length)
1da177e4 145{
4fd8da8d 146 return do_sys_truncate(path, length);
1da177e4
LT
147}
148
3f6d078d
AV
149#ifdef CONFIG_COMPAT
150COMPAT_SYSCALL_DEFINE2(truncate, const char __user *, path, compat_off_t, length)
151{
152 return do_sys_truncate(path, length);
153}
154#endif
155
5f0d594c 156long do_ftruncate(struct file *file, loff_t length, int small)
1da177e4 157{
bf2965d5 158 struct inode *inode;
1da177e4 159 struct dentry *dentry;
1da177e4
LT
160 int error;
161
1da177e4 162 /* explicitly opened as large or we are on 64-bit box */
5f0d594c 163 if (file->f_flags & O_LARGEFILE)
1da177e4
LT
164 small = 0;
165
5f0d594c 166 dentry = file->f_path.dentry;
1da177e4 167 inode = dentry->d_inode;
5f0d594c
TS
168 if (!S_ISREG(inode->i_mode) || !(file->f_mode & FMODE_WRITE))
169 return -EINVAL;
1da177e4 170
1da177e4
LT
171 /* Cannot ftruncate over 2^31 bytes without large file support */
172 if (small && length > MAX_NON_LFS)
5f0d594c 173 return -EINVAL;
1da177e4 174
78757af6 175 /* Check IS_APPEND on real upper inode */
5f0d594c
TS
176 if (IS_APPEND(file_inode(file)))
177 return -EPERM;
14da9200 178 sb_start_write(inode->i_sb);
5f0d594c 179 error = security_file_truncate(file);
1da177e4 180 if (!error)
5f0d594c
TS
181 error = do_truncate(file_mnt_idmap(file), dentry, length,
182 ATTR_MTIME | ATTR_CTIME, file);
14da9200 183 sb_end_write(inode->i_sb);
5f0d594c
TS
184
185 return error;
186}
187
188long do_sys_ftruncate(unsigned int fd, loff_t length, int small)
189{
190 struct fd f;
191 int error;
192
193 if (length < 0)
194 return -EINVAL;
195 f = fdget(fd);
196 if (!f.file)
197 return -EBADF;
198
199 error = do_ftruncate(f.file, length, small);
200
2903ff01 201 fdput(f);
1da177e4
LT
202 return error;
203}
204
4b8e88e5 205SYSCALL_DEFINE2(ftruncate, unsigned int, fd, off_t, length)
1da177e4 206{
2cf09666 207 return do_sys_ftruncate(fd, length, 1);
1da177e4
LT
208}
209
3f6d078d 210#ifdef CONFIG_COMPAT
4b8e88e5 211COMPAT_SYSCALL_DEFINE2(ftruncate, unsigned int, fd, compat_off_t, length)
3f6d078d
AV
212{
213 return do_sys_ftruncate(fd, length, 1);
214}
215#endif
216
1da177e4
LT
217/* LFS versions of truncate are only needed on 32 bit machines */
218#if BITS_PER_LONG == 32
4a0fd5bf 219SYSCALL_DEFINE2(truncate64, const char __user *, path, loff_t, length)
1da177e4
LT
220{
221 return do_sys_truncate(path, length);
222}
223
4a0fd5bf 224SYSCALL_DEFINE2(ftruncate64, unsigned int, fd, loff_t, length)
1da177e4 225{
2cf09666 226 return do_sys_ftruncate(fd, length, 0);
1da177e4 227}
6673e0c3 228#endif /* BITS_PER_LONG == 32 */
1da177e4 229
59c10c52
GR
230#if defined(CONFIG_COMPAT) && defined(__ARCH_WANT_COMPAT_TRUNCATE64)
231COMPAT_SYSCALL_DEFINE3(truncate64, const char __user *, pathname,
232 compat_arg_u64_dual(length))
233{
234 return ksys_truncate(pathname, compat_arg_u64_glue(length));
235}
236#endif
237
238#if defined(CONFIG_COMPAT) && defined(__ARCH_WANT_COMPAT_FTRUNCATE64)
239COMPAT_SYSCALL_DEFINE3(ftruncate64, unsigned int, fd,
240 compat_arg_u64_dual(length))
241{
242 return ksys_ftruncate(fd, compat_arg_u64_glue(length));
243}
244#endif
3e63cbb1 245
72c72bdf 246int vfs_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
97ac7350 247{
496ad9aa 248 struct inode *inode = file_inode(file);
3e63cbb1 249 long ret;
23cc6ef6 250 loff_t sum;
97ac7350
AA
251
252 if (offset < 0 || len <= 0)
3e63cbb1 253 return -EINVAL;
97ac7350 254
57413d8e 255 if (mode & ~(FALLOC_FL_MODE_MASK | FALLOC_FL_KEEP_SIZE))
409332b6
LC
256 return -EOPNOTSUPP;
257
57413d8e
CH
258 /*
259 * Modes are exclusive, even if that is not obvious from the encoding
260 * as bit masks and the mix with the flag in the same namespace.
261 *
262 * To make things even more complicated, FALLOC_FL_ALLOCATE_RANGE is
263 * encoded as no bit set.
264 */
265 switch (mode & FALLOC_FL_MODE_MASK) {
266 case FALLOC_FL_ALLOCATE_RANGE:
267 case FALLOC_FL_UNSHARE_RANGE:
268 case FALLOC_FL_ZERO_RANGE:
269 break;
270 case FALLOC_FL_PUNCH_HOLE:
271 if (!(mode & FALLOC_FL_KEEP_SIZE))
272 return -EOPNOTSUPP;
273 break;
274 case FALLOC_FL_COLLAPSE_RANGE:
275 case FALLOC_FL_INSERT_RANGE:
276 if (mode & FALLOC_FL_KEEP_SIZE)
277 return -EOPNOTSUPP;
278 break;
279 default:
3e63cbb1 280 return -EOPNOTSUPP;
57413d8e 281 }
71be6b49 282
97ac7350 283 if (!(file->f_mode & FMODE_WRITE))
3e63cbb1 284 return -EBADF;
1ca551c6 285
00f5e619 286 /*
57413d8e 287 * On append-only files only space preallocation is supported.
00f5e619 288 */
8fc61d92 289 if ((mode & ~FALLOC_FL_KEEP_SIZE) && IS_APPEND(inode))
1ca551c6
MS
290 return -EPERM;
291
292 if (IS_IMMUTABLE(inode))
293 return -EPERM;
294
0790b31b 295 /*
6d2b6170 296 * We cannot allow any fallocate operation on an active swapfile
0790b31b
LC
297 */
298 if (IS_SWAPFILE(inode))
6d2b6170 299 return -ETXTBSY;
0790b31b 300
97ac7350
AA
301 /*
302 * Revalidate the write permissions, in case security policy has
303 * changed since the files were opened.
304 */
305 ret = security_file_permission(file, MAY_WRITE);
306 if (ret)
3e63cbb1 307 return ret;
97ac7350 308
d9e5d310
AG
309 ret = fsnotify_file_area_perm(file, MAY_WRITE, &offset, len);
310 if (ret)
311 return ret;
312
97ac7350 313 if (S_ISFIFO(inode->i_mode))
3e63cbb1 314 return -ESPIPE;
97ac7350 315
9e79b132
AG
316 if (S_ISDIR(inode->i_mode))
317 return -EISDIR;
318
319 if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))
3e63cbb1 320 return -ENODEV;
97ac7350 321
23cc6ef6
JS
322 /* Check for wraparound */
323 if (check_add_overflow(offset, len, &sum))
324 return -EFBIG;
325
326 if (sum > inode->i_sb->s_maxbytes)
3e63cbb1 327 return -EFBIG;
97ac7350 328
2fe17c10 329 if (!file->f_op->fallocate)
3e63cbb1 330 return -EOPNOTSUPP;
97ac7350 331
bfe219d3 332 file_start_write(file);
14da9200 333 ret = file->f_op->fallocate(file, mode, offset, len);
820c12d5
HS
334
335 /*
336 * Create inotify and fanotify events.
337 *
338 * To keep the logic simple always create events if fallocate succeeds.
339 * This implies that events are even created if the file size remains
340 * unchanged, e.g. when using flag FALLOC_FL_KEEP_SIZE.
341 */
342 if (ret == 0)
343 fsnotify_modify(file);
344
bfe219d3 345 file_end_write(file);
14da9200 346 return ret;
3e63cbb1 347}
72c72bdf 348EXPORT_SYMBOL_GPL(vfs_fallocate);
3e63cbb1 349
edf292c7 350int ksys_fallocate(int fd, int mode, loff_t offset, loff_t len)
3e63cbb1 351{
2903ff01 352 struct fd f = fdget(fd);
3e63cbb1
AJ
353 int error = -EBADF;
354
2903ff01 355 if (f.file) {
72c72bdf 356 error = vfs_fallocate(f.file, mode, offset, len);
2903ff01 357 fdput(f);
3e63cbb1 358 }
3e63cbb1 359 return error;
97ac7350 360}
3e63cbb1 361
edf292c7
DB
362SYSCALL_DEFINE4(fallocate, int, fd, int, mode, loff_t, offset, loff_t, len)
363{
364 return ksys_fallocate(fd, mode, offset, len);
365}
366
59c10c52
GR
367#if defined(CONFIG_COMPAT) && defined(__ARCH_WANT_COMPAT_FALLOCATE)
368COMPAT_SYSCALL_DEFINE6(fallocate, int, fd, int, mode, compat_arg_u64_dual(offset),
369 compat_arg_u64_dual(len))
370{
371 return ksys_fallocate(fd, mode, compat_arg_u64_glue(offset),
372 compat_arg_u64_glue(len));
373}
374#endif
375
1da177e4
LT
376/*
377 * access() needs to use the real uid/gid, not the effective uid/gid.
378 * We do this by temporarily clearing all FS-related capabilities and
379 * switching the fsuid/fsgid around to the real ones.
981ee95c
MG
380 *
381 * Creating new credentials is expensive, so we try to skip doing it,
382 * which we can if the result would match what we already got.
1da177e4 383 */
981ee95c
MG
384static bool access_need_override_creds(int flags)
385{
386 const struct cred *cred;
387
388 if (flags & AT_EACCESS)
389 return false;
390
391 cred = current_cred();
392 if (!uid_eq(cred->fsuid, cred->uid) ||
393 !gid_eq(cred->fsgid, cred->gid))
394 return true;
395
396 if (!issecure(SECURE_NO_SETUID_FIXUP)) {
397 kuid_t root_uid = make_kuid(cred->user_ns, 0);
398 if (!uid_eq(cred->uid, root_uid)) {
399 if (!cap_isclear(cred->cap_effective))
400 return true;
401 } else {
402 if (!cap_isidentical(cred->cap_effective,
403 cred->cap_permitted))
404 return true;
405 }
406 }
407
408 return false;
409}
410
94704515 411static const struct cred *access_override_creds(void)
1da177e4 412{
d84f4f99
DH
413 const struct cred *old_cred;
414 struct cred *override_cred;
1da177e4 415
d84f4f99
DH
416 override_cred = prepare_creds();
417 if (!override_cred)
94704515 418 return NULL;
1da177e4 419
981ee95c
MG
420 /*
421 * XXX access_need_override_creds performs checks in hopes of skipping
422 * this work. Make sure it stays in sync if making any changes in this
423 * routine.
424 */
425
d84f4f99
DH
426 override_cred->fsuid = override_cred->uid;
427 override_cred->fsgid = override_cred->gid;
1da177e4 428
086f7316 429 if (!issecure(SECURE_NO_SETUID_FIXUP)) {
1cdcbec1 430 /* Clear the capabilities if we switch to a non-root user */
18815a18
EB
431 kuid_t root_uid = make_kuid(override_cred->user_ns, 0);
432 if (!uid_eq(override_cred->uid, root_uid))
d84f4f99 433 cap_clear(override_cred->cap_effective);
086f7316 434 else
d84f4f99
DH
435 override_cred->cap_effective =
436 override_cred->cap_permitted;
086f7316 437 }
1da177e4 438
d7852fbd
LT
439 /*
440 * The new set of credentials can *only* be used in
441 * task-synchronous circumstances, and does not need
442 * RCU freeing, unless somebody then takes a separate
443 * reference to it.
444 *
445 * NOTE! This is _only_ true because this credential
446 * is used purely for override_creds() that installs
447 * it as the subjective cred. Other threads will be
448 * accessing ->real_cred, not the subjective cred.
449 *
450 * If somebody _does_ make a copy of this (using the
451 * 'get_current_cred()' function), that will clear the
452 * non_rcu field, because now that other user may be
453 * expecting RCU freeing. But normal thread-synchronous
d2185690
BS
454 * cred accesses will keep things non-racy to avoid RCU
455 * freeing.
d7852fbd
LT
456 */
457 override_cred->non_rcu = 1;
458
d84f4f99 459 old_cred = override_creds(override_cred);
94704515
MS
460
461 /* override_cred() gets its own ref */
462 put_cred(override_cred);
463
464 return old_cred;
465}
466
eb9d7d39 467static long do_faccessat(int dfd, const char __user *filename, int mode, int flags)
94704515
MS
468{
469 struct path path;
470 struct inode *inode;
471 int res;
472 unsigned int lookup_flags = LOOKUP_FOLLOW;
c8ffd8bc 473 const struct cred *old_cred = NULL;
94704515
MS
474
475 if (mode & ~S_IRWXO) /* where's F_OK, X_OK, W_OK, R_OK? */
476 return -EINVAL;
477
c8ffd8bc
MS
478 if (flags & ~(AT_EACCESS | AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH))
479 return -EINVAL;
480
481 if (flags & AT_SYMLINK_NOFOLLOW)
482 lookup_flags &= ~LOOKUP_FOLLOW;
483 if (flags & AT_EMPTY_PATH)
484 lookup_flags |= LOOKUP_EMPTY;
485
981ee95c 486 if (access_need_override_creds(flags)) {
c8ffd8bc
MS
487 old_cred = access_override_creds();
488 if (!old_cred)
489 return -ENOMEM;
490 }
94704515 491
87fa5595
JL
492retry:
493 res = user_path_at(dfd, filename, lookup_flags, &path);
6902d925
DH
494 if (res)
495 goto out;
496
63afdfc7 497 inode = d_backing_inode(path.dentry);
256984a8
AV
498
499 if ((mode & MAY_EXEC) && S_ISREG(inode->i_mode)) {
30524472
AV
500 /*
501 * MAY_EXEC on regular files is denied if the fs is mounted
502 * with the "noexec" flag.
503 */
504 res = -EACCES;
90f8572b 505 if (path_noexec(&path))
30524472
AV
506 goto out_path_release;
507 }
508
4609e1f1 509 res = inode_permission(mnt_idmap(path.mnt), inode, mode | MAY_ACCESS);
6902d925 510 /* SuS v2 requires we report a read only fs too */
256984a8 511 if (res || !(mode & S_IWOTH) || special_file(inode->i_mode))
6902d925 512 goto out_path_release;
2f676cbc
DH
513 /*
514 * This is a rare case where using __mnt_is_readonly()
515 * is OK without a mnt_want/drop_write() pair. Since
516 * no actual write to the fs is performed here, we do
517 * not need to telegraph to that to anyone.
518 *
519 * By doing this, we accept that this access is
520 * inherently racy and know that the fs may change
521 * state before we even see this result.
522 */
2d8f3038 523 if (__mnt_is_readonly(path.mnt))
6902d925 524 res = -EROFS;
1da177e4 525
6902d925 526out_path_release:
2d8f3038 527 path_put(&path);
87fa5595
JL
528 if (retry_estale(res, lookup_flags)) {
529 lookup_flags |= LOOKUP_REVAL;
530 goto retry;
531 }
6902d925 532out:
c8ffd8bc
MS
533 if (old_cred)
534 revert_creds(old_cred);
535
1da177e4
LT
536 return res;
537}
538
cbfe20f5
DB
539SYSCALL_DEFINE3(faccessat, int, dfd, const char __user *, filename, int, mode)
540{
c8ffd8bc
MS
541 return do_faccessat(dfd, filename, mode, 0);
542}
543
544SYSCALL_DEFINE4(faccessat2, int, dfd, const char __user *, filename, int, mode,
545 int, flags)
546{
547 return do_faccessat(dfd, filename, mode, flags);
cbfe20f5
DB
548}
549
ca013e94 550SYSCALL_DEFINE2(access, const char __user *, filename, int, mode)
5590ff0d 551{
c8ffd8bc 552 return do_faccessat(AT_FDCWD, filename, mode, 0);
5590ff0d
UD
553}
554
db63f1e3 555SYSCALL_DEFINE1(chdir, const char __user *, filename)
1da177e4 556{
2d8f3038 557 struct path path;
1da177e4 558 int error;
0291c0a5
JL
559 unsigned int lookup_flags = LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
560retry:
561 error = user_path_at(AT_FDCWD, filename, lookup_flags, &path);
1da177e4
LT
562 if (error)
563 goto out;
564
02f92b38 565 error = path_permission(&path, MAY_EXEC | MAY_CHDIR);
1da177e4
LT
566 if (error)
567 goto dput_and_out;
568
2d8f3038 569 set_fs_pwd(current->fs, &path);
1da177e4
LT
570
571dput_and_out:
2d8f3038 572 path_put(&path);
0291c0a5
JL
573 if (retry_estale(error, lookup_flags)) {
574 lookup_flags |= LOOKUP_REVAL;
575 goto retry;
576 }
1da177e4
LT
577out:
578 return error;
579}
580
3cdad428 581SYSCALL_DEFINE1(fchdir, unsigned int, fd)
1da177e4 582{
2903ff01 583 struct fd f = fdget_raw(fd);
159b0956 584 int error;
1da177e4
LT
585
586 error = -EBADF;
2903ff01 587 if (!f.file)
1da177e4
LT
588 goto out;
589
1da177e4 590 error = -ENOTDIR;
159b0956 591 if (!d_can_lookup(f.file->f_path.dentry))
1da177e4
LT
592 goto out_putf;
593
02f92b38 594 error = file_permission(f.file, MAY_EXEC | MAY_CHDIR);
1da177e4 595 if (!error)
2903ff01 596 set_fs_pwd(current->fs, &f.file->f_path);
1da177e4 597out_putf:
2903ff01 598 fdput(f);
1da177e4
LT
599out:
600 return error;
601}
602
4b7ca501 603SYSCALL_DEFINE1(chroot, const char __user *, filename)
1da177e4 604{
2d8f3038 605 struct path path;
1da177e4 606 int error;
2771261e
JL
607 unsigned int lookup_flags = LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
608retry:
609 error = user_path_at(AT_FDCWD, filename, lookup_flags, &path);
1da177e4
LT
610 if (error)
611 goto out;
612
02f92b38 613 error = path_permission(&path, MAY_EXEC | MAY_CHDIR);
1da177e4
LT
614 if (error)
615 goto dput_and_out;
616
617 error = -EPERM;
c7b96acf 618 if (!ns_capable(current_user_ns(), CAP_SYS_CHROOT))
1da177e4 619 goto dput_and_out;
8b8efb44
TH
620 error = security_path_chroot(&path);
621 if (error)
622 goto dput_and_out;
1da177e4 623
2d8f3038 624 set_fs_root(current->fs, &path);
1da177e4
LT
625 error = 0;
626dput_and_out:
2d8f3038 627 path_put(&path);
2771261e
JL
628 if (retry_estale(error, lookup_flags)) {
629 lookup_flags |= LOOKUP_REVAL;
630 goto retry;
631 }
1da177e4
LT
632out:
633 return error;
634}
635
1097742e 636int chmod_common(const struct path *path, umode_t mode)
1da177e4 637{
e57712eb 638 struct inode *inode = path->dentry->d_inode;
27ac0ffe 639 struct inode *delegated_inode = NULL;
1da177e4 640 struct iattr newattrs;
e57712eb 641 int error;
1da177e4 642
e57712eb
AV
643 error = mnt_want_write(path->mnt);
644 if (error)
645 return error;
27ac0ffe 646retry_deleg:
5955102c 647 inode_lock(inode);
cdcf116d 648 error = security_path_chmod(path, mode);
e57712eb 649 if (error)
fe542cf5 650 goto out_unlock;
1da177e4
LT
651 newattrs.ia_mode = (mode & S_IALLUGO) | (inode->i_mode & ~S_IALLUGO);
652 newattrs.ia_valid = ATTR_MODE | ATTR_CTIME;
abf08576 653 error = notify_change(mnt_idmap(path->mnt), path->dentry,
b8b546a0 654 &newattrs, &delegated_inode);
fe542cf5 655out_unlock:
5955102c 656 inode_unlock(inode);
27ac0ffe
BF
657 if (delegated_inode) {
658 error = break_deleg_wait(&delegated_inode);
659 if (!error)
660 goto retry_deleg;
661 }
e57712eb
AV
662 mnt_drop_write(path->mnt);
663 return error;
664}
665
9e96c8c0
CH
666int vfs_fchmod(struct file *file, umode_t mode)
667{
668 audit_file(file);
669 return chmod_common(&file->f_path, mode);
670}
671
b25ba7c3 672SYSCALL_DEFINE2(fchmod, unsigned int, fd, umode_t, mode)
e57712eb 673{
173c8401 674 struct fd f = fdget(fd);
e57712eb
AV
675 int err = -EBADF;
676
173c8401 677 if (f.file) {
9e96c8c0 678 err = vfs_fchmod(f.file, mode);
173c8401 679 fdput(f);
e57712eb 680 }
1da177e4
LT
681 return err;
682}
683
09da082b
AG
684static int do_fchmodat(int dfd, const char __user *filename, umode_t mode,
685 unsigned int flags)
1da177e4 686{
2d8f3038 687 struct path path;
1da177e4 688 int error;
09da082b
AG
689 unsigned int lookup_flags;
690
5daeb41a 691 if (unlikely(flags & ~(AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH)))
09da082b
AG
692 return -EINVAL;
693
694 lookup_flags = (flags & AT_SYMLINK_NOFOLLOW) ? 0 : LOOKUP_FOLLOW;
5daeb41a
AS
695 if (flags & AT_EMPTY_PATH)
696 lookup_flags |= LOOKUP_EMPTY;
09da082b 697
14ff690c
JL
698retry:
699 error = user_path_at(dfd, filename, lookup_flags, &path);
e57712eb
AV
700 if (!error) {
701 error = chmod_common(&path, mode);
702 path_put(&path);
14ff690c
JL
703 if (retry_estale(error, lookup_flags)) {
704 lookup_flags |= LOOKUP_REVAL;
705 goto retry;
706 }
e57712eb 707 }
1da177e4
LT
708 return error;
709}
710
09da082b
AG
711SYSCALL_DEFINE4(fchmodat2, int, dfd, const char __user *, filename,
712 umode_t, mode, unsigned int, flags)
713{
714 return do_fchmodat(dfd, filename, mode, flags);
715}
716
03450e27
DB
717SYSCALL_DEFINE3(fchmodat, int, dfd, const char __user *, filename,
718 umode_t, mode)
719{
09da082b 720 return do_fchmodat(dfd, filename, mode, 0);
03450e27
DB
721}
722
49f0a076 723SYSCALL_DEFINE2(chmod, const char __user *, filename, umode_t, mode)
5590ff0d 724{
09da082b 725 return do_fchmodat(AT_FDCWD, filename, mode, 0);
5590ff0d
UD
726}
727
55650b2f 728/*
b27c82e1
CB
729 * Check whether @kuid is valid and if so generate and set vfsuid_t in
730 * ia_vfsuid.
731 *
732 * Return: true if @kuid is valid, false if not.
733 */
734static inline bool setattr_vfsuid(struct iattr *attr, kuid_t kuid)
735{
736 if (!uid_valid(kuid))
737 return false;
738 attr->ia_valid |= ATTR_UID;
739 attr->ia_vfsuid = VFSUIDT_INIT(kuid);
740 return true;
741}
742
55650b2f 743/*
b27c82e1
CB
744 * Check whether @kgid is valid and if so generate and set vfsgid_t in
745 * ia_vfsgid.
746 *
747 * Return: true if @kgid is valid, false if not.
748 */
749static inline bool setattr_vfsgid(struct iattr *attr, kgid_t kgid)
750{
751 if (!gid_valid(kgid))
752 return false;
753 attr->ia_valid |= ATTR_GID;
754 attr->ia_vfsgid = VFSGIDT_INIT(kgid);
755 return true;
756}
757
b873498f 758int chown_common(const struct path *path, uid_t user, gid_t group)
1da177e4 759{
abf08576 760 struct mnt_idmap *idmap;
4d7ca409 761 struct user_namespace *fs_userns;
fe542cf5 762 struct inode *inode = path->dentry->d_inode;
27ac0ffe 763 struct inode *delegated_inode = NULL;
1da177e4
LT
764 int error;
765 struct iattr newattrs;
52137abe
EB
766 kuid_t uid;
767 kgid_t gid;
768
769 uid = make_kuid(current_user_ns(), user);
770 gid = make_kgid(current_user_ns(), group);
1da177e4 771
abf08576 772 idmap = mnt_idmap(path->mnt);
bd303368 773 fs_userns = i_user_ns(inode);
b8b546a0 774
c1b8940b 775retry_deleg:
f52d74b1
TH
776 newattrs.ia_vfsuid = INVALID_VFSUID;
777 newattrs.ia_vfsgid = INVALID_VFSGID;
1da177e4 778 newattrs.ia_valid = ATTR_CTIME;
b27c82e1
CB
779 if ((user != (uid_t)-1) && !setattr_vfsuid(&newattrs, uid))
780 return -EINVAL;
781 if ((group != (gid_t)-1) && !setattr_vfsgid(&newattrs, gid))
782 return -EINVAL;
5955102c 783 inode_lock(inode);
ed5a7047
CB
784 if (!S_ISDIR(inode->i_mode))
785 newattrs.ia_valid |= ATTR_KILL_SUID | ATTR_KILL_PRIV |
9452e93e 786 setattr_should_drop_sgid(idmap, inode);
b27c82e1
CB
787 /* Continue to send actual fs values, not the mount values. */
788 error = security_path_chown(
789 path,
4d7ca409
CB
790 from_vfsuid(idmap, fs_userns, newattrs.ia_vfsuid),
791 from_vfsgid(idmap, fs_userns, newattrs.ia_vfsgid));
fe542cf5 792 if (!error)
abf08576 793 error = notify_change(idmap, path->dentry, &newattrs,
2f221d6f 794 &delegated_inode);
5955102c 795 inode_unlock(inode);
27ac0ffe
BF
796 if (delegated_inode) {
797 error = break_deleg_wait(&delegated_inode);
798 if (!error)
799 goto retry_deleg;
800 }
1da177e4
LT
801 return error;
802}
803
55731b3c
DB
804int do_fchownat(int dfd, const char __user *filename, uid_t user, gid_t group,
805 int flag)
5590ff0d 806{
2d8f3038 807 struct path path;
5590ff0d 808 int error = -EINVAL;
65cfc672 809 int lookup_flags;
5590ff0d 810
65cfc672 811 if ((flag & ~(AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH)) != 0)
5590ff0d
UD
812 goto out;
813
65cfc672
AV
814 lookup_flags = (flag & AT_SYMLINK_NOFOLLOW) ? 0 : LOOKUP_FOLLOW;
815 if (flag & AT_EMPTY_PATH)
816 lookup_flags |= LOOKUP_EMPTY;
99a5df37 817retry:
65cfc672 818 error = user_path_at(dfd, filename, lookup_flags, &path);
6902d925
DH
819 if (error)
820 goto out;
2d8f3038 821 error = mnt_want_write(path.mnt);
2af482a7
DH
822 if (error)
823 goto out_release;
fe542cf5 824 error = chown_common(&path, user, group);
2d8f3038 825 mnt_drop_write(path.mnt);
2af482a7 826out_release:
2d8f3038 827 path_put(&path);
99a5df37
JL
828 if (retry_estale(error, lookup_flags)) {
829 lookup_flags |= LOOKUP_REVAL;
830 goto retry;
831 }
5590ff0d
UD
832out:
833 return error;
834}
835
55731b3c
DB
836SYSCALL_DEFINE5(fchownat, int, dfd, const char __user *, filename, uid_t, user,
837 gid_t, group, int, flag)
838{
839 return do_fchownat(dfd, filename, user, group, flag);
840}
841
55e4def0 842SYSCALL_DEFINE3(chown, const char __user *, filename, uid_t, user, gid_t, group)
1da177e4 843{
55731b3c 844 return do_fchownat(AT_FDCWD, filename, user, group, 0);
55e4def0 845}
1da177e4 846
55e4def0
DH
847SYSCALL_DEFINE3(lchown, const char __user *, filename, uid_t, user, gid_t, group)
848{
55731b3c
DB
849 return do_fchownat(AT_FDCWD, filename, user, group,
850 AT_SYMLINK_NOFOLLOW);
1da177e4
LT
851}
852
c04011fe
CH
853int vfs_fchown(struct file *file, uid_t user, gid_t group)
854{
855 int error;
856
857 error = mnt_want_write_file(file);
858 if (error)
859 return error;
860 audit_file(file);
861 error = chown_common(&file->f_path, user, group);
862 mnt_drop_write_file(file);
863 return error;
864}
865
55731b3c 866int ksys_fchown(unsigned int fd, uid_t user, gid_t group)
1da177e4 867{
2903ff01 868 struct fd f = fdget(fd);
1da177e4
LT
869 int error = -EBADF;
870
c04011fe
CH
871 if (f.file) {
872 error = vfs_fchown(f.file, user, group);
873 fdput(f);
874 }
1da177e4
LT
875 return error;
876}
877
55731b3c
DB
878SYSCALL_DEFINE3(fchown, unsigned int, fd, uid_t, user, gid_t, group)
879{
880 return ksys_fchown(fd, user, group);
881}
882
83bc1d29
AG
883static inline int file_get_write_access(struct file *f)
884{
885 int error;
886
887 error = get_write_access(f->f_inode);
888 if (unlikely(error))
889 return error;
890 error = mnt_get_write_access(f->f_path.mnt);
891 if (unlikely(error))
892 goto cleanup_inode;
893 if (unlikely(f->f_mode & FMODE_BACKING)) {
def3ae83 894 error = mnt_get_write_access(backing_file_user_path(f)->mnt);
83bc1d29
AG
895 if (unlikely(error))
896 goto cleanup_mnt;
897 }
898 return 0;
899
900cleanup_mnt:
901 mnt_put_write_access(f->f_path.mnt);
902cleanup_inode:
903 put_write_access(f->f_inode);
904 return error;
905}
906
02e5180d 907static int do_dentry_open(struct file *f,
ae2bb293 908 int (*open)(struct inode *, struct file *))
1da177e4 909{
1abf0c71 910 static const struct file_operations empty_fops = {};
0f4a2ceb 911 struct inode *inode = f->f_path.dentry->d_inode;
1da177e4
LT
912 int error;
913
b5bcdda3 914 path_get(&f->f_path);
4bacc9c9 915 f->f_inode = inode;
1da177e4 916 f->f_mapping = inode->i_mapping;
5660e13d 917 f->f_wb_err = filemap_sample_wb_err(f->f_mapping);
735e4ae5 918 f->f_sb_err = file_sample_sb_err(f);
5660e13d 919
3f4d5a00 920 if (unlikely(f->f_flags & O_PATH)) {
f5d11409 921 f->f_mode = FMODE_PATH | FMODE_OPENED;
1abf0c71 922 f->f_op = &empty_fops;
af04fadc 923 return 0;
1abf0c71
AV
924 }
925
d6da19c9
AG
926 if ((f->f_mode & (FMODE_READ | FMODE_WRITE)) == FMODE_READ) {
927 i_readcount_inc(inode);
928 } else if (f->f_mode & FMODE_WRITE && !special_file(inode->i_mode)) {
83bc1d29 929 error = file_get_write_access(f);
3f4d5a00 930 if (unlikely(error))
1da177e4 931 goto cleanup_file;
83f936c7 932 f->f_mode |= FMODE_WRITER;
1da177e4
LT
933 }
934
2be7d348
LT
935 /* POSIX.1-2008/SUSv4 Section XSI 2.9.7 */
936 if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode))
937 f->f_mode |= FMODE_ATOMIC_POS;
938
1abf0c71 939 f->f_op = fops_get(inode->i_fop);
7159d544 940 if (WARN_ON(!f->f_op)) {
72c2d531
AV
941 error = -ENODEV;
942 goto cleanup_all;
943 }
1abf0c71 944
e3f20ae2 945 error = security_file_open(f);
788e7dd4
YN
946 if (error)
947 goto cleanup_all;
948
c65454a9 949 error = break_lease(file_inode(f), f->f_flags);
f3c7691e
BF
950 if (error)
951 goto cleanup_all;
952
ea73ea72
AV
953 /* normally all 3 are set; ->open() can clear them if needed */
954 f->f_mode |= FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE;
72c2d531 955 if (!open)
834f2a4a
TM
956 open = f->f_op->open;
957 if (open) {
958 error = open(inode, f);
1da177e4
LT
959 if (error)
960 goto cleanup_all;
961 }
f5d11409 962 f->f_mode |= FMODE_OPENED;
293bc982 963 if ((f->f_mode & FMODE_READ) &&
84363182 964 likely(f->f_op->read || f->f_op->read_iter))
7f7f25e8 965 f->f_mode |= FMODE_CAN_READ;
293bc982 966 if ((f->f_mode & FMODE_WRITE) &&
84363182 967 likely(f->f_op->write || f->f_op->write_iter))
7f7f25e8 968 f->f_mode |= FMODE_CAN_WRITE;
e7478158
JD
969 if ((f->f_mode & FMODE_LSEEK) && !f->f_op->llseek)
970 f->f_mode &= ~FMODE_LSEEK;
a2ad63da
N
971 if (f->f_mapping->a_ops && f->f_mapping->a_ops->direct_IO)
972 f->f_mode |= FMODE_CAN_ODIRECT;
834f2a4a 973
1da177e4 974 f->f_flags &= ~(O_CREAT | O_EXCL | O_NOCTTY | O_TRUNC);
164f4064 975 f->f_iocb_flags = iocb_flags(f);
1da177e4
LT
976
977 file_ra_state_init(&f->f_ra, f->f_mapping->host->i_mapping);
af04fadc 978
a2ad63da
N
979 if ((f->f_flags & O_DIRECT) && !(f->f_mode & FMODE_CAN_ODIRECT))
980 return -EINVAL;
09d91cda
SL
981
982 /*
983 * XXX: Huge page cache doesn't support writing yet. Drop all page
984 * cache for this file before processing writes.
985 */
eb6ecbed
CF
986 if (f->f_mode & FMODE_WRITE) {
987 /*
8e344782
MG
988 * Depends on full fence from get_write_access() to synchronize
989 * against collapse_file() regarding i_writecount and nr_thps
990 * updates. Ensures subsequent insertion of THPs into the page
991 * cache will fail.
eb6ecbed 992 */
55fc0d91 993 if (filemap_nr_thps(inode->i_mapping)) {
8468e937
RW
994 struct address_space *mapping = inode->i_mapping;
995
55fc0d91 996 filemap_invalidate_lock(inode->i_mapping);
8468e937
RW
997 /*
998 * unmap_mapping_range just need to be called once
999 * here, because the private pages is not need to be
1000 * unmapped mapping (e.g. data segment of dynamic
1001 * shared libraries here).
1002 */
1003 unmap_mapping_range(mapping, 0, 0, 0);
1004 truncate_inode_pages(mapping, 0);
55fc0d91
RW
1005 filemap_invalidate_unlock(inode->i_mapping);
1006 }
eb6ecbed 1007 }
09d91cda 1008
96b7e579 1009 return 0;
1da177e4
LT
1010
1011cleanup_all:
6b4e8085
AV
1012 if (WARN_ON_ONCE(error > 0))
1013 error = -EINVAL;
1da177e4 1014 fops_put(f->f_op);
d6da19c9 1015 put_file_access(f);
1da177e4 1016cleanup_file:
02e5180d
AV
1017 path_put(&f->f_path);
1018 f->f_path.mnt = NULL;
1019 f->f_path.dentry = NULL;
dd37978c 1020 f->f_inode = NULL;
96b7e579 1021 return error;
1da177e4
LT
1022}
1023
d18e9008
MS
1024/**
1025 * finish_open - finish opening a file
0854d450 1026 * @file: file pointer
d18e9008
MS
1027 * @dentry: pointer to dentry
1028 * @open: open callback
1029 *
1030 * This can be used to finish opening a file passed to i_op->atomic_open().
1031 *
1032 * If the open callback is set to NULL, then the standard f_op->open()
1033 * filesystem callback is substituted.
0854d450
MS
1034 *
1035 * NB: the dentry reference is _not_ consumed. If, for example, the dentry is
1036 * the return value of d_splice_alias(), then the caller needs to perform dput()
1037 * on it after finish_open().
1038 *
0854d450 1039 * Returns zero on success or -errno if the open failed.
d18e9008 1040 */
30d90494 1041int finish_open(struct file *file, struct dentry *dentry,
be12af3e 1042 int (*open)(struct inode *, struct file *))
d18e9008 1043{
aad888f8 1044 BUG_ON(file->f_mode & FMODE_OPENED); /* once it's opened, it's opened */
d18e9008 1045
b5bcdda3 1046 file->f_path.dentry = dentry;
0f4a2ceb 1047 return do_dentry_open(file, open);
d18e9008
MS
1048}
1049EXPORT_SYMBOL(finish_open);
1050
1051/**
1052 * finish_no_open - finish ->atomic_open() without opening the file
1053 *
0854d450 1054 * @file: file pointer
d18e9008
MS
1055 * @dentry: dentry or NULL (as returned from ->lookup())
1056 *
1057 * This can be used to set the result of a successful lookup in ->atomic_open().
0854d450
MS
1058 *
1059 * NB: unlike finish_open() this function does consume the dentry reference and
1060 * the caller need not dput() it.
1061 *
64e1ac4d 1062 * Returns "0" which must be the return value of ->atomic_open() after having
0854d450 1063 * called this function.
d18e9008 1064 */
e45198a6 1065int finish_no_open(struct file *file, struct dentry *dentry)
d18e9008 1066{
30d90494 1067 file->f_path.dentry = dentry;
64e1ac4d 1068 return 0;
d18e9008
MS
1069}
1070EXPORT_SYMBOL(finish_no_open);
1071
9bf39ab2
MS
1072char *file_path(struct file *filp, char *buf, int buflen)
1073{
1074 return d_path(&filp->f_path, buf, buflen);
1075}
1076EXPORT_SYMBOL(file_path);
1077
4bacc9c9
DH
1078/**
1079 * vfs_open - open the file at the given path
1080 * @path: path to open
1081 * @file: newly allocated file with f_flag initialized
4bacc9c9 1082 */
ae2bb293 1083int vfs_open(const struct path *path, struct file *file)
4bacc9c9 1084{
7d1cf5e6
N
1085 int ret;
1086
54d5ca87 1087 file->f_path = *path;
7d1cf5e6
N
1088 ret = do_dentry_open(file, NULL);
1089 if (!ret) {
1090 /*
1091 * Once we return a file with FMODE_OPENED, __fput() will call
1092 * fsnotify_close(), so we need fsnotify_open() here for
1093 * symmetry.
1094 */
1095 fsnotify_open(file);
1096 }
1097 return ret;
4bacc9c9
DH
1098}
1099
765927b2 1100struct file *dentry_open(const struct path *path, int flags,
745ca247 1101 const struct cred *cred)
a1a5b3d9
PS
1102{
1103 int error;
1104 struct file *f;
1105
c212f9aa 1106 /* We must always pass in a valid mount pointer. */
765927b2 1107 BUG_ON(!path->mnt);
322ee5b3 1108
ea73ea72 1109 f = alloc_empty_file(flags, cred);
af04fadc 1110 if (!IS_ERR(f)) {
ae2bb293 1111 error = vfs_open(path, f);
4d27f326
AV
1112 if (error) {
1113 fput(f);
af04fadc
AV
1114 f = ERR_PTR(error);
1115 }
2a027e7a
AV
1116 }
1117 return f;
a1a5b3d9 1118}
1da177e4
LT
1119EXPORT_SYMBOL(dentry_open);
1120
fb70bf12
CL
1121/**
1122 * dentry_create - Create and open a file
1123 * @path: path to create
1124 * @flags: O_ flags
1125 * @mode: mode bits for new file
1126 * @cred: credentials to use
1127 *
1128 * Caller must hold the parent directory's lock, and have prepared
1129 * a negative dentry, placed in @path->dentry, for the new file.
1130 *
1131 * Caller sets @path->mnt to the vfsmount of the filesystem where
1132 * the new file is to be created. The parent directory and the
1133 * negative dentry must reside on the same filesystem instance.
1134 *
1135 * On success, returns a "struct file *". Otherwise a ERR_PTR
1136 * is returned.
1137 */
1138struct file *dentry_create(const struct path *path, int flags, umode_t mode,
1139 const struct cred *cred)
1140{
1141 struct file *f;
1142 int error;
1143
fb70bf12
CL
1144 f = alloc_empty_file(flags, cred);
1145 if (IS_ERR(f))
1146 return f;
1147
abf08576 1148 error = vfs_create(mnt_idmap(path->mnt),
fb70bf12
CL
1149 d_inode(path->dentry->d_parent),
1150 path->dentry, mode, true);
1151 if (!error)
1152 error = vfs_open(path, f);
1153
1154 if (unlikely(error)) {
1155 fput(f);
1156 return ERR_PTR(error);
1157 }
1158 return f;
1159}
1160EXPORT_SYMBOL(dentry_create);
1161
cbb0b9d4
AG
1162/**
1163 * kernel_file_open - open a file for kernel internal use
1164 * @path: path of the file to open
1165 * @flags: open flags
cbb0b9d4
AG
1166 * @cred: credentials for open
1167 *
1168 * Open a file for use by in-kernel consumers. The file is not accounted
1169 * against nr_files and must not be installed into the file descriptor
1170 * table.
1171 *
1172 * Return: Opened file on success, an error pointer on failure.
1173 */
1174struct file *kernel_file_open(const struct path *path, int flags,
af58dc1f 1175 const struct cred *cred)
2abc77af 1176{
cbb0b9d4
AG
1177 struct file *f;
1178 int error;
2abc77af 1179
cbb0b9d4
AG
1180 f = alloc_empty_file_noaccount(flags, cred);
1181 if (IS_ERR(f))
1182 return f;
1183
1184 f->f_path = *path;
0f4a2ceb 1185 error = do_dentry_open(f, NULL);
cbb0b9d4
AG
1186 if (error) {
1187 fput(f);
7d1cf5e6 1188 return ERR_PTR(error);
2abc77af 1189 }
7d1cf5e6
N
1190
1191 fsnotify_open(f);
2abc77af
AV
1192 return f;
1193}
cbb0b9d4
AG
1194EXPORT_SYMBOL_GPL(kernel_file_open);
1195
fddb5d43
AS
1196#define WILL_CREATE(flags) (flags & (O_CREAT | __O_TMPFILE))
1197#define O_PATH_FLAGS (O_DIRECTORY | O_NOFOLLOW | O_PATH | O_CLOEXEC)
1198
35cb6d54 1199inline struct open_how build_open_how(int flags, umode_t mode)
fddb5d43
AS
1200{
1201 struct open_how how = {
1202 .flags = flags & VALID_OPEN_FLAGS,
1203 .mode = mode & S_IALLUGO,
1204 };
1205
1206 /* O_PATH beats everything else. */
1207 if (how.flags & O_PATH)
1208 how.flags &= O_PATH_FLAGS;
1209 /* Modes should only be set for create-like flags. */
1210 if (!WILL_CREATE(how.flags))
1211 how.mode = 0;
1212 return how;
1213}
1214
35cb6d54 1215inline int build_open_flags(const struct open_how *how, struct open_flags *op)
47c805dc 1216{
cfe80306 1217 u64 flags = how->flags;
cedd0bdc 1218 u64 strip = __FMODE_NONOTIFY | O_CLOEXEC;
47c805dc 1219 int lookup_flags = 0;
62fb4a15 1220 int acc_mode = ACC_MODE(flags);
47c805dc 1221
cfe80306
CB
1222 BUILD_BUG_ON_MSG(upper_32_bits(VALID_OPEN_FLAGS),
1223 "struct open_flags doesn't yet handle flags > 32 bits");
1224
1225 /*
1226 * Strip flags that either shouldn't be set by userspace like
1227 * FMODE_NONOTIFY or that aren't relevant in determining struct
1228 * open_flags like O_CLOEXEC.
1229 */
1230 flags &= ~strip;
fddb5d43 1231
629e014b 1232 /*
fddb5d43
AS
1233 * Older syscalls implicitly clear all of the invalid flags or argument
1234 * values before calling build_open_flags(), but openat2(2) checks all
1235 * of its arguments.
629e014b 1236 */
fddb5d43
AS
1237 if (flags & ~VALID_OPEN_FLAGS)
1238 return -EINVAL;
1239 if (how->resolve & ~VALID_RESOLVE_FLAGS)
1240 return -EINVAL;
629e014b 1241
398840f8
AS
1242 /* Scoping flags are mutually exclusive. */
1243 if ((how->resolve & RESOLVE_BENEATH) && (how->resolve & RESOLVE_IN_ROOT))
1244 return -EINVAL;
1245
fddb5d43
AS
1246 /* Deal with the mode. */
1247 if (WILL_CREATE(flags)) {
1248 if (how->mode & ~S_IALLUGO)
1249 return -EINVAL;
1250 op->mode = how->mode | S_IFREG;
1251 } else {
1252 if (how->mode != 0)
1253 return -EINVAL;
e68726ff 1254 op->mode = 0;
fddb5d43 1255 }
47c805dc
AV
1256
1257 /*
43b45063
CB
1258 * Block bugs where O_DIRECTORY | O_CREAT created regular files.
1259 * Note, that blocking O_DIRECTORY | O_CREAT here also protects
1260 * O_TMPFILE below which requires O_DIRECTORY being raised.
47c805dc 1261 */
43b45063
CB
1262 if ((flags & (O_DIRECTORY | O_CREAT)) == (O_DIRECTORY | O_CREAT))
1263 return -EINVAL;
1264
1265 /* Now handle the creative implementation of O_TMPFILE. */
bb458c64 1266 if (flags & __O_TMPFILE) {
43b45063
CB
1267 /*
1268 * In order to ensure programs get explicit errors when trying
1269 * to use O_TMPFILE on old kernels we enforce that O_DIRECTORY
1270 * is raised alongside __O_TMPFILE.
1271 */
1272 if (!(flags & O_DIRECTORY))
60545d0d 1273 return -EINVAL;
ba57ea64
AV
1274 if (!(acc_mode & MAY_WRITE))
1275 return -EINVAL;
fddb5d43
AS
1276 }
1277 if (flags & O_PATH) {
1278 /* O_PATH only permits certain other flags to be set. */
1279 if (flags & ~O_PATH_FLAGS)
1280 return -EINVAL;
1abf0c71 1281 acc_mode = 0;
1abf0c71 1282 }
47c805dc 1283
fddb5d43
AS
1284 /*
1285 * O_SYNC is implemented as __O_SYNC|O_DSYNC. As many places only
1286 * check for O_DSYNC if the need any syncing at all we enforce it's
1287 * always set instead of having to deal with possibly weird behaviour
1288 * for malicious applications setting only __O_SYNC.
1289 */
1290 if (flags & __O_SYNC)
1291 flags |= O_DSYNC;
1292
1abf0c71 1293 op->open_flag = flags;
47c805dc
AV
1294
1295 /* O_TRUNC implies we need access checks for write permissions */
1296 if (flags & O_TRUNC)
1297 acc_mode |= MAY_WRITE;
1298
1299 /* Allow the LSM permission hook to distinguish append
1300 access from general write access. */
1301 if (flags & O_APPEND)
1302 acc_mode |= MAY_APPEND;
1303
1304 op->acc_mode = acc_mode;
1305
1abf0c71
AV
1306 op->intent = flags & O_PATH ? 0 : LOOKUP_OPEN;
1307
47c805dc
AV
1308 if (flags & O_CREAT) {
1309 op->intent |= LOOKUP_CREATE;
31d1726d 1310 if (flags & O_EXCL) {
47c805dc 1311 op->intent |= LOOKUP_EXCL;
31d1726d
AV
1312 flags |= O_NOFOLLOW;
1313 }
47c805dc
AV
1314 }
1315
1316 if (flags & O_DIRECTORY)
1317 lookup_flags |= LOOKUP_DIRECTORY;
1318 if (!(flags & O_NOFOLLOW))
1319 lookup_flags |= LOOKUP_FOLLOW;
fddb5d43
AS
1320
1321 if (how->resolve & RESOLVE_NO_XDEV)
1322 lookup_flags |= LOOKUP_NO_XDEV;
1323 if (how->resolve & RESOLVE_NO_MAGICLINKS)
1324 lookup_flags |= LOOKUP_NO_MAGICLINKS;
1325 if (how->resolve & RESOLVE_NO_SYMLINKS)
1326 lookup_flags |= LOOKUP_NO_SYMLINKS;
1327 if (how->resolve & RESOLVE_BENEATH)
1328 lookup_flags |= LOOKUP_BENEATH;
1329 if (how->resolve & RESOLVE_IN_ROOT)
1330 lookup_flags |= LOOKUP_IN_ROOT;
99668f61
JA
1331 if (how->resolve & RESOLVE_CACHED) {
1332 /* Don't bother even trying for create/truncate/tmpfile open */
a0fc452a 1333 if (flags & (O_TRUNC | O_CREAT | __O_TMPFILE))
99668f61
JA
1334 return -EAGAIN;
1335 lookup_flags |= LOOKUP_CACHED;
1336 }
fddb5d43 1337
f9652e10
AV
1338 op->lookup_flags = lookup_flags;
1339 return 0;
47c805dc
AV
1340}
1341
669abf4e
JL
1342/**
1343 * file_open_name - open file and return file pointer
1344 *
1345 * @name: struct filename containing path to open
1346 * @flags: open flags as per the open(2) second argument
1347 * @mode: mode for the new file if O_CREAT is set, else ignored
1348 *
1349 * This is the helper to open a file from kernelspace if you really
1350 * have to. But in generally you should not do this, so please move
1351 * along, nothing to see here..
1352 */
1353struct file *file_open_name(struct filename *name, int flags, umode_t mode)
1354{
1355 struct open_flags op;
fddb5d43
AS
1356 struct open_how how = build_open_how(flags, mode);
1357 int err = build_open_flags(&how, &op);
1358 if (err)
1359 return ERR_PTR(err);
1360 return do_filp_open(AT_FDCWD, name, &op);
669abf4e
JL
1361}
1362
47c805dc
AV
1363/**
1364 * filp_open - open file and return file pointer
1365 *
1366 * @filename: path to open
1367 * @flags: open flags as per the open(2) second argument
1368 * @mode: mode for the new file if O_CREAT is set, else ignored
1369 *
1370 * This is the helper to open a file from kernelspace if you really
1371 * have to. But in generally you should not do this, so please move
1372 * along, nothing to see here..
1373 */
a218d0fd 1374struct file *filp_open(const char *filename, int flags, umode_t mode)
47c805dc 1375{
51689104
PM
1376 struct filename *name = getname_kernel(filename);
1377 struct file *file = ERR_CAST(name);
a69ce85e 1378
51689104
PM
1379 if (!IS_ERR(name)) {
1380 file = file_open_name(name, flags, mode);
1381 putname(name);
1382 }
1383 return file;
47c805dc
AV
1384}
1385EXPORT_SYMBOL(filp_open);
1386
ffb37ca3 1387struct file *file_open_root(const struct path *root,
378c6520 1388 const char *filename, int flags, umode_t mode)
73d049a4
AV
1389{
1390 struct open_flags op;
fddb5d43
AS
1391 struct open_how how = build_open_how(flags, mode);
1392 int err = build_open_flags(&how, &op);
f9652e10
AV
1393 if (err)
1394 return ERR_PTR(err);
ffb37ca3 1395 return do_file_open_root(root, filename, &op);
73d049a4
AV
1396}
1397EXPORT_SYMBOL(file_open_root);
1398
fddb5d43
AS
1399static long do_sys_openat2(int dfd, const char __user *filename,
1400 struct open_how *how)
1da177e4 1401{
47c805dc 1402 struct open_flags op;
fddb5d43 1403 int fd = build_open_flags(how, &op);
f9652e10
AV
1404 struct filename *tmp;
1405
1406 if (fd)
1407 return fd;
1408
1409 tmp = getname(filename);
1410 if (IS_ERR(tmp))
1411 return PTR_ERR(tmp);
1412
fddb5d43 1413 fd = get_unused_fd_flags(how->flags);
f9652e10
AV
1414 if (fd >= 0) {
1415 struct file *f = do_filp_open(dfd, tmp, &op);
1416 if (IS_ERR(f)) {
1417 put_unused_fd(fd);
1418 fd = PTR_ERR(f);
1419 } else {
f9652e10 1420 fd_install(fd, f);
1da177e4 1421 }
1da177e4 1422 }
f9652e10 1423 putname(tmp);
1da177e4 1424 return fd;
1da177e4 1425}
e922efc3 1426
fddb5d43 1427long do_sys_open(int dfd, const char __user *filename, int flags, umode_t mode)
e922efc3 1428{
fddb5d43
AS
1429 struct open_how how = build_open_how(flags, mode);
1430 return do_sys_openat2(dfd, filename, &how);
1431}
e922efc3 1432
fddb5d43
AS
1433
1434SYSCALL_DEFINE3(open, const char __user *, filename, int, flags, umode_t, mode)
1435{
166e07c3
CH
1436 if (force_o_largefile())
1437 flags |= O_LARGEFILE;
1438 return do_sys_open(AT_FDCWD, filename, flags, mode);
e922efc3 1439}
1da177e4 1440
6559eed8 1441SYSCALL_DEFINE4(openat, int, dfd, const char __user *, filename, int, flags,
a218d0fd 1442 umode_t, mode)
5590ff0d
UD
1443{
1444 if (force_o_largefile())
1445 flags |= O_LARGEFILE;
2cf09666 1446 return do_sys_open(dfd, filename, flags, mode);
5590ff0d 1447}
5590ff0d 1448
fddb5d43
AS
1449SYSCALL_DEFINE4(openat2, int, dfd, const char __user *, filename,
1450 struct open_how __user *, how, size_t, usize)
1451{
1452 int err;
1453 struct open_how tmp;
1454
1455 BUILD_BUG_ON(sizeof(struct open_how) < OPEN_HOW_SIZE_VER0);
1456 BUILD_BUG_ON(sizeof(struct open_how) != OPEN_HOW_SIZE_LATEST);
1457
1458 if (unlikely(usize < OPEN_HOW_SIZE_VER0))
1459 return -EINVAL;
1460
1461 err = copy_struct_from_user(&tmp, sizeof(tmp), how, usize);
1462 if (err)
1463 return err;
1464
571e5c0e
RGB
1465 audit_openat2_how(&tmp);
1466
fddb5d43
AS
1467 /* O_LARGEFILE is only allowed for non-O_PATH. */
1468 if (!(tmp.flags & O_PATH) && force_o_largefile())
1469 tmp.flags |= O_LARGEFILE;
1470
1471 return do_sys_openat2(dfd, filename, &tmp);
1472}
1473
e35d49f6
AV
1474#ifdef CONFIG_COMPAT
1475/*
1476 * Exactly like sys_open(), except that it doesn't set the
1477 * O_LARGEFILE flag.
1478 */
1479COMPAT_SYSCALL_DEFINE3(open, const char __user *, filename, int, flags, umode_t, mode)
1480{
1481 return do_sys_open(AT_FDCWD, filename, flags, mode);
1482}
1483
1484/*
1485 * Exactly like sys_openat(), except that it doesn't set the
1486 * O_LARGEFILE flag.
1487 */
1488COMPAT_SYSCALL_DEFINE4(openat, int, dfd, const char __user *, filename, int, flags, umode_t, mode)
1489{
1490 return do_sys_open(dfd, filename, flags, mode);
1491}
1492#endif
1493
1da177e4
LT
1494#ifndef __alpha__
1495
1496/*
1497 * For backward compatibility? Maybe this should be moved
1498 * into arch/i386 instead?
1499 */
a218d0fd 1500SYSCALL_DEFINE2(creat, const char __user *, pathname, umode_t, mode)
1da177e4 1501{
166e07c3 1502 int flags = O_CREAT | O_WRONLY | O_TRUNC;
1da177e4 1503
166e07c3
CH
1504 if (force_o_largefile())
1505 flags |= O_LARGEFILE;
1506 return do_sys_open(AT_FDCWD, pathname, flags, mode);
1507}
1da177e4
LT
1508#endif
1509
1510/*
1511 * "id" is the POSIX thread ID. We use the
1512 * files pointer for this..
1513 */
021a160a 1514static int filp_flush(struct file *filp, fl_owner_t id)
1da177e4 1515{
45778ca8 1516 int retval = 0;
1da177e4 1517
47d58691
JH
1518 if (CHECK_DATA_CORRUPTION(file_count(filp) == 0,
1519 "VFS: Close: file count is 0 (f_op=%ps)",
1520 filp->f_op)) {
45778ca8 1521 return 0;
1da177e4
LT
1522 }
1523
72c2d531 1524 if (filp->f_op->flush)
75e1fcc0 1525 retval = filp->f_op->flush(filp, id);
1da177e4 1526
1abf0c71
AV
1527 if (likely(!(filp->f_mode & FMODE_PATH))) {
1528 dnotify_flush(filp, id);
1529 locks_remove_posix(filp, id);
1530 }
1da177e4
LT
1531 return retval;
1532}
1533
021a160a
LT
1534int filp_close(struct file *filp, fl_owner_t id)
1535{
1536 int retval;
1537
1538 retval = filp_flush(filp, id);
1539 fput(filp);
1540
1541 return retval;
1542}
1da177e4
LT
1543EXPORT_SYMBOL(filp_close);
1544
1545/*
1546 * Careful here! We test whether the file pointer is NULL before
1547 * releasing the fd. This ensures that one clone task can't release
1548 * an fd while another clone is opening it.
1549 */
ca013e94 1550SYSCALL_DEFINE1(close, unsigned int, fd)
1da177e4 1551{
021a160a
LT
1552 int retval;
1553 struct file *file;
1554
a88c955f 1555 file = file_close_fd(fd);
021a160a
LT
1556 if (!file)
1557 return -EBADF;
1558
1559 retval = filp_flush(file, current->files);
1560
1561 /*
1562 * We're returning to user space. Don't bother
1563 * with any delayed fput() cases.
1564 */
1565 __fput_sync(file);
ee731f4f
EP
1566
1567 /* can't restart close syscall because file table entry was cleared */
1568 if (unlikely(retval == -ERESTARTSYS ||
1569 retval == -ERESTARTNOINTR ||
1570 retval == -ERESTARTNOHAND ||
1571 retval == -ERESTART_RESTARTBLOCK))
1572 retval = -EINTR;
1573
1574 return retval;
1da177e4 1575}
1da177e4 1576
278a5fba 1577/**
35931eb3 1578 * sys_close_range() - Close all file descriptors in a given range.
278a5fba
CB
1579 *
1580 * @fd: starting file descriptor to close
1581 * @max_fd: last file descriptor to close
1582 * @flags: reserved for future extensions
1583 *
1584 * This closes a range of file descriptors. All file descriptors
1585 * from @fd up to and including @max_fd are closed.
1586 * Currently, errors to close a given file descriptor are ignored.
1587 */
1588SYSCALL_DEFINE3(close_range, unsigned int, fd, unsigned int, max_fd,
1589 unsigned int, flags)
1590{
60997c3d 1591 return __close_range(fd, max_fd, flags);
278a5fba
CB
1592}
1593
1da177e4
LT
1594/*
1595 * This routine simulates a hangup on the tty, to arrange that users
1596 * are given clean terminals at login time.
1597 */
ca013e94 1598SYSCALL_DEFINE0(vhangup)
1da177e4
LT
1599{
1600 if (capable(CAP_SYS_TTY_CONFIG)) {
2cb5998b 1601 tty_vhangup_self();
1da177e4
LT
1602 return 0;
1603 }
1604 return -EPERM;
1605}
1606
1607/*
1608 * Called when an inode is about to be open.
1609 * We use this to disallow opening large files on 32bit systems if
1610 * the caller didn't specify O_LARGEFILE. On 64bit systems we force
1611 * on this flag in sys_open.
1612 */
1613int generic_file_open(struct inode * inode, struct file * filp)
1614{
1615 if (!(filp->f_flags & O_LARGEFILE) && i_size_read(inode) > MAX_NON_LFS)
a9c62a18 1616 return -EOVERFLOW;
1da177e4
LT
1617 return 0;
1618}
1619
1620EXPORT_SYMBOL(generic_file_open);
1621
1622/*
1623 * This is used by subsystems that don't want seekable
06b1e104
DT
1624 * file descriptors. The function is not supposed to ever fail, the only
1625 * reason it returns an 'int' and not 'void' is so that it can be plugged
1626 * directly into file_operations structure.
1da177e4
LT
1627 */
1628int nonseekable_open(struct inode *inode, struct file *filp)
1629{
1630 filp->f_mode &= ~(FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE);
1631 return 0;
1632}
1633
1634EXPORT_SYMBOL(nonseekable_open);
10dce8af
KS
1635
1636/*
1637 * stream_open is used by subsystems that want stream-like file descriptors.
1638 * Such file descriptors are not seekable and don't have notion of position
438ab720
KS
1639 * (file.f_pos is always 0 and ppos passed to .read()/.write() is always NULL).
1640 * Contrary to file descriptors of other regular files, .read() and .write()
1641 * can run simultaneously.
10dce8af
KS
1642 *
1643 * stream_open never fails and is marked to return int so that it could be
1644 * directly used as file_operations.open .
1645 */
1646int stream_open(struct inode *inode, struct file *filp)
1647{
2be7d348 1648 filp->f_mode &= ~(FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE | FMODE_ATOMIC_POS);
10dce8af
KS
1649 filp->f_mode |= FMODE_STREAM;
1650 return 0;
1651}
1652
1653EXPORT_SYMBOL(stream_open);