1 /*
2 * Copyright (c) 2000-2020 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
29 /*
30 * Copyright (c) 1982, 1986, 1989, 1993
31 * The Regents of the University of California. All rights reserved.
32 * (c) UNIX System Laboratories, Inc.
33 * All or some portions of this file are derived from material licensed
34 * to the University of California by American Telephone and Telegraph
35 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
36 * the permission of UNIX System Laboratories, Inc.
37 *
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
40 * are met:
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. All advertising materials mentioning features or use of this software
47 * must display the following acknowledgement:
48 * This product includes software developed by the University of
49 * California, Berkeley and its contributors.
50 * 4. Neither the name of the University nor the names of its contributors
51 * may be used to endorse or promote products derived from this software
52 * without specific prior written permission.
53 *
54 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64 * SUCH DAMAGE.
65 *
66 * @(#)vfs_vnops.c 8.14 (Berkeley) 6/15/95
67 *
68 */
69 /*
70 * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
71 * support for mandatory and extensible security protections. This notice
72 * is included in support of clause 2.2 (b) of the Apple Public License,
73 * Version 2.0.
74 */
75
76 #include <sys/param.h>
77 #include <sys/types.h>
78 #include <sys/systm.h>
79 #include <sys/kernel.h>
80 #include <sys/file_internal.h>
81 #include <sys/stat.h>
82 #include <sys/proc_internal.h>
83 #include <sys/kauth.h>
84 #include <sys/mount_internal.h>
85 #include <sys/namei.h>
86 #include <sys/vnode_internal.h>
87 #include <sys/ioctl.h>
88 #include <sys/fsctl.h>
89 #include <sys/tty.h>
90 #include <sys/ubc.h>
91 #include <sys/conf.h>
92 #include <sys/disk.h>
93 #include <sys/fsevents.h>
94 #include <sys/kdebug.h>
95 #include <sys/xattr.h>
96 #include <sys/ubc_internal.h>
97 #include <sys/uio_internal.h>
98 #include <sys/resourcevar.h>
99 #include <sys/signalvar.h>
100
101 #include <vm/vm_kern.h>
102 #include <vm/vm_map.h>
103
104 #include <miscfs/specfs/specdev.h>
105 #include <miscfs/fifofs/fifo.h>
106
107 #if CONFIG_MACF
108 #include <security/mac_framework.h>
109 #endif
110
111 #include <IOKit/IOBSD.h>
112 #include <libkern/section_keywords.h>
113
114 static int vn_closefile(struct fileglob *fp, vfs_context_t ctx);
115 static int vn_ioctl(struct fileproc *fp, u_long com, caddr_t data,
116 vfs_context_t ctx);
117 static int vn_read(struct fileproc *fp, struct uio *uio, int flags,
118 vfs_context_t ctx);
119 static int vn_write(struct fileproc *fp, struct uio *uio, int flags,
120 vfs_context_t ctx);
121 static int vn_select( struct fileproc *fp, int which, void * wql,
122 vfs_context_t ctx);
123 static int vn_kqfilter(struct fileproc *fp, struct knote *kn,
124 struct kevent_qos_s *kev);
125 static void filt_vndetach(struct knote *kn);
126 static int filt_vnode(struct knote *kn, long hint);
127 static int filt_vnode_common(struct knote *kn, struct kevent_qos_s *kev,
128 vnode_t vp, long hint);
129 static int vn_open_auth_finish(vnode_t vp, int fmode, vfs_context_t ctx);
130
131 const struct fileops vnops = {
132 .fo_type = DTYPE_VNODE,
133 .fo_read = vn_read,
134 .fo_write = vn_write,
135 .fo_ioctl = vn_ioctl,
136 .fo_select = vn_select,
137 .fo_close = vn_closefile,
138 .fo_drain = fo_no_drain,
139 .fo_kqfilter = vn_kqfilter,
140 };
141
142 static int filt_vntouch(struct knote *kn, struct kevent_qos_s *kev);
143 static int filt_vnprocess(struct knote *kn, struct kevent_qos_s*kev);
144
145 SECURITY_READ_ONLY_EARLY(struct filterops) vnode_filtops = {
146 .f_isfd = 1,
147 .f_attach = NULL,
148 .f_detach = filt_vndetach,
149 .f_event = filt_vnode,
150 .f_touch = filt_vntouch,
151 .f_process = filt_vnprocess,
152 };
153
154 /*
155 * Common code for vnode open operations.
156 * Check permissions, and call the VNOP_OPEN or VNOP_CREATE routine.
157 *
158 * XXX the profusion of interfaces here is probably a bad thing.
159 */
160 int
vn_open(struct nameidata * ndp,int fmode,int cmode)161 vn_open(struct nameidata *ndp, int fmode, int cmode)
162 {
163 return vn_open_modflags(ndp, &fmode, cmode);
164 }
165
166 int
vn_open_modflags(struct nameidata * ndp,int * fmodep,int cmode)167 vn_open_modflags(struct nameidata *ndp, int *fmodep, int cmode)
168 {
169 int error;
170 struct vnode_attr *vap;
171
172 vap = kalloc_type(struct vnode_attr, Z_WAITOK);
173
174 VATTR_INIT(vap);
175 VATTR_SET(vap, va_mode, (mode_t)cmode);
176
177 error = vn_open_auth(ndp, fmodep, vap, NULLVP);
178
179 kfree_type(struct vnode_attr, vap);
180
181 return error;
182 }
183
184 static int
vn_open_auth_finish(vnode_t vp,int fmode,vfs_context_t ctx)185 vn_open_auth_finish(vnode_t vp, int fmode, vfs_context_t ctx)
186 {
187 int error;
188
189 if ((error = vnode_ref_ext(vp, fmode, 0)) != 0) {
190 goto bad;
191 }
192
193 /* Call out to allow 3rd party notification of open.
194 * Ignore result of kauth_authorize_fileop call.
195 */
196 #if CONFIG_MACF
197 mac_vnode_notify_open(ctx, vp, fmode);
198 #endif
199 kauth_authorize_fileop(vfs_context_ucred(ctx), KAUTH_FILEOP_OPEN,
200 (uintptr_t)vp, 0);
201
202 return 0;
203
204 bad:
205 return error;
206 }
207
208 /*
209 * May do nameidone() to allow safely adding an FSEvent. Cue off of ni_dvp to
210 * determine whether that has happened.
211 */
212 static int
vn_open_auth_do_create(struct nameidata * ndp,struct vnode_attr * vap,int fmode,boolean_t * did_create,boolean_t * did_open,vfs_context_t ctx)213 vn_open_auth_do_create(struct nameidata *ndp, struct vnode_attr *vap, int fmode, boolean_t *did_create, boolean_t *did_open, vfs_context_t ctx)
214 {
215 uint32_t status = 0;
216 vnode_t dvp = ndp->ni_dvp;
217 int batched;
218 int error;
219 vnode_t vp;
220
221 batched = vnode_compound_open_available(ndp->ni_dvp);
222 *did_open = FALSE;
223
224 VATTR_SET(vap, va_type, VREG);
225 if (fmode & O_EXCL) {
226 vap->va_vaflags |= VA_EXCLUSIVE;
227 }
228
229 #if NAMEDRSRCFORK
230 if (ndp->ni_cnd.cn_flags & CN_WANTSRSRCFORK) {
231 if ((error = vn_authorize_create(dvp, &ndp->ni_cnd, vap, ctx, NULL)) != 0) {
232 goto out;
233 }
234 if ((error = vnode_makenamedstream(dvp, &ndp->ni_vp, XATTR_RESOURCEFORK_NAME, 0, ctx)) != 0) {
235 goto out;
236 }
237 *did_create = TRUE;
238 } else {
239 #endif
240 if (!batched) {
241 if ((error = vn_authorize_create(dvp, &ndp->ni_cnd, vap, ctx, NULL)) != 0) {
242 goto out;
243 }
244 }
245
246 error = vn_create(dvp, &ndp->ni_vp, ndp, vap, VN_CREATE_DOOPEN, fmode, &status, ctx);
247 if (error != 0) {
248 if (batched) {
249 *did_create = (status & COMPOUND_OPEN_STATUS_DID_CREATE) ? TRUE : FALSE;
250 } else {
251 *did_create = FALSE;
252 }
253
254 if (error == EKEEPLOOKING) {
255 if (*did_create) {
256 panic("EKEEPLOOKING, but we did a create?");
257 }
258 if (!batched) {
259 panic("EKEEPLOOKING from filesystem that doesn't support compound vnops?");
260 }
261 if ((ndp->ni_flag & NAMEI_CONTLOOKUP) == 0) {
262 panic("EKEEPLOOKING, but continue flag not set?");
263 }
264
265 /*
266 * Do NOT drop the dvp: we need everything to continue the lookup.
267 */
268 return error;
269 }
270 } else {
271 if (batched) {
272 *did_create = (status & COMPOUND_OPEN_STATUS_DID_CREATE) ? 1 : 0;
273 *did_open = TRUE;
274 } else {
275 *did_create = TRUE;
276 }
277 }
278 #if NAMEDRSRCFORK
279 }
280 #endif
281
282 vp = ndp->ni_vp;
283
284 if (*did_create) {
285 int update_flags = 0;
286
287 // Make sure the name & parent pointers are hooked up
288 if (vp->v_name == NULL) {
289 update_flags |= VNODE_UPDATE_NAME;
290 }
291 if (vp->v_parent == NULLVP) {
292 update_flags |= VNODE_UPDATE_PARENT;
293 }
294
295 if (update_flags) {
296 vnode_update_identity(vp, dvp, ndp->ni_cnd.cn_nameptr, ndp->ni_cnd.cn_namelen, ndp->ni_cnd.cn_hash, update_flags);
297 }
298
299 vnode_put(dvp);
300 ndp->ni_dvp = NULLVP;
301
302 #if CONFIG_FSE
303 if (need_fsevent(FSE_CREATE_FILE, vp)) {
304 add_fsevent(FSE_CREATE_FILE, ctx,
305 FSE_ARG_VNODE, vp,
306 FSE_ARG_DONE);
307 }
308 #endif
309 }
310 out:
311 if (ndp->ni_dvp != NULLVP) {
312 vnode_put(dvp);
313 ndp->ni_dvp = NULLVP;
314 }
315
316 return error;
317 }
318
319 /*
320 * This is the number of times we'll loop in vn_open_auth without explicitly
321 * yielding the CPU when we determine we have to retry.
322 */
323 #define RETRY_NO_YIELD_COUNT 5
324
325 /*
326 * Open a file with authorization, updating the contents of the structures
327 * pointed to by ndp, fmodep, and vap as necessary to perform the requested
328 * operation. This function is used for both opens of existing files, and
329 * creation of new files.
330 *
331 * Parameters: ndp The nami data pointer describing the
332 * file
333 * fmodep A pointer to an int containg the mode
334 * information to be used for the open
335 * vap A pointer to the vnode attribute
336 * descriptor to be used for the open
337 * authvp If non-null and VA_DP_AUTHENTICATE is set in vap,
338 * have a supporting filesystem verify that the file
339 * to be opened is on the same volume as authvp and
340 * that authvp is on an authenticated volume
341 *
342 * Indirect: * Contents of the data structures pointed
343 * to by the parameters are modified as
344 * necessary to the requested operation.
345 *
346 * Returns: 0 Success
347 * !0 errno value
348 *
349 * Notes: The kauth_filesec_t in 'vap', if any, is in host byte order.
350 *
351 * The contents of '*ndp' will be modified, based on the other
352 * arguments to this function, and to return file and directory
353 * data necessary to satisfy the requested operation.
354 *
355 * If the file does not exist and we are creating it, then the
356 * O_TRUNC flag will be cleared in '*fmodep' to indicate to the
357 * caller that the file was not truncated.
358 *
359 * If the file exists and the O_EXCL flag was not specified, then
360 * the O_CREAT flag will be cleared in '*fmodep' to indicate to
361 * the caller that the existing file was merely opened rather
362 * than created.
363 *
364 * The contents of '*vap' will be modified as necessary to
365 * complete the operation, including setting of supported
366 * attribute, clearing of fields containing unsupported attributes
367 * in the request, if the request proceeds without them, etc..
368 *
369 * XXX: This function is too complicated in actings on its arguments
370 *
371 * XXX: We should enummerate the possible errno values here, and where
372 * in the code they originated.
373 */
374 int
vn_open_auth(struct nameidata * ndp,int * fmodep,struct vnode_attr * vap,vnode_t authvp)375 vn_open_auth(struct nameidata *ndp, int *fmodep, struct vnode_attr *vap, vnode_t authvp)
376 {
377 struct vnode *vp;
378 struct vnode *dvp;
379 vfs_context_t ctx = ndp->ni_cnd.cn_context;
380 int error;
381 int fmode;
382 uint32_t origcnflags;
383 boolean_t did_create;
384 boolean_t did_open;
385 boolean_t need_vnop_open;
386 boolean_t batched;
387 boolean_t ref_failed;
388 int nretries = 0;
389
390 again:
391 vp = NULL;
392 dvp = NULL;
393 batched = FALSE;
394 did_create = FALSE;
395 need_vnop_open = TRUE;
396 ref_failed = FALSE;
397 fmode = *fmodep;
398 origcnflags = ndp->ni_cnd.cn_flags;
399
400 if (VATTR_IS_ACTIVE(vap, va_dataprotect_flags)) {
401 if ((authvp != NULLVP)
402 && !ISSET(vap->va_dataprotect_flags, VA_DP_AUTHENTICATE)) {
403 error = EINVAL;
404 goto out;
405 }
406 // If raw encrypted mode is requested, handle that here
407 if (ISSET(vap->va_dataprotect_flags, VA_DP_RAWENCRYPTED)) {
408 fmode |= FENCRYPTED;
409 }
410 }
411
412 if ((fmode & O_NOFOLLOW_ANY) && (fmode & O_NOFOLLOW)) {
413 error = EINVAL;
414 goto out;
415 }
416
417 /*
418 * We only call nameidone when exiting the function because we may
419 * end up needing the pathname buffer in the component structure.
420 */
421
422 /*
423 * O_CREAT
424 */
425 if (fmode & O_CREAT) {
426 if ((fmode & O_DIRECTORY)) {
427 error = EINVAL;
428 goto out;
429 }
430 ndp->ni_cnd.cn_nameiop = CREATE;
431 #if CONFIG_TRIGGERS
432 ndp->ni_op = OP_LINK;
433 #endif
434 /* Inherit USEDVP, vnode_open() supported flags only */
435 ndp->ni_cnd.cn_flags &= (USEDVP | NOCROSSMOUNT);
436 ndp->ni_cnd.cn_flags |= LOCKPARENT | LOCKLEAF | AUDITVNPATH1;
437 /* Inherit NAMEI_ROOTDIR flag only */
438 ndp->ni_flag &= NAMEI_ROOTDIR;
439 ndp->ni_flag |= NAMEI_COMPOUNDOPEN;
440 #if NAMEDRSRCFORK
441 /* open calls are allowed for resource forks. */
442 ndp->ni_cnd.cn_flags |= CN_ALLOWRSRCFORK;
443 #endif
444 if ((fmode & O_EXCL) == 0 && (fmode & O_NOFOLLOW) == 0 && (origcnflags & FOLLOW) != 0) {
445 ndp->ni_cnd.cn_flags |= FOLLOW;
446 }
447 if (fmode & O_NOFOLLOW_ANY) {
448 /* will return ELOOP on the first symlink to be hit */
449 ndp->ni_flag |= NAMEI_NOFOLLOW_ANY;
450 }
451
452 continue_create_lookup:
453 if ((error = namei(ndp))) {
454 goto out;
455 }
456
457 dvp = ndp->ni_dvp;
458 vp = ndp->ni_vp;
459
460 batched = vnode_compound_open_available(dvp);
461
462 /* not found, create */
463 if (vp == NULL) {
464 /* must have attributes for a new file */
465 if (vap == NULL) {
466 vnode_put(dvp);
467 error = EINVAL;
468 goto out;
469 }
470 /*
471 * Attempt a create. For a system supporting compound VNOPs, we may
472 * find an existing file or create one; in either case, we will already
473 * have the file open and no VNOP_OPEN() will be needed.
474 */
475 error = vn_open_auth_do_create(ndp, vap, fmode, &did_create, &did_open, ctx);
476
477 dvp = ndp->ni_dvp;
478 vp = ndp->ni_vp;
479
480 /* Detected a node that the filesystem couldn't handle */
481 if (error == EKEEPLOOKING) {
482 if (!batched) {
483 panic("EKEEPLOOKING from a filesystem that doesn't support compound VNOPs?");
484 }
485 goto continue_create_lookup;
486 }
487
488 if (dvp) {
489 panic("Shouldn't have a dvp here.");
490 }
491
492 if (error) {
493 /*
494 * Check for a create race.
495 */
496 if ((error == EEXIST) && !(fmode & O_EXCL)) {
497 if (vp) {
498 vnode_put(vp);
499 }
500 nameidone(ndp);
501 goto again;
502 }
503 goto bad;
504 }
505
506 need_vnop_open = !did_open;
507 } else {
508 if (fmode & O_EXCL) {
509 error = EEXIST;
510 }
511
512 /*
513 * We have a vnode. Use compound open if available
514 * or else fall through to "traditional" path. Note: can't
515 * do a compound open for root, because the parent belongs
516 * to a different FS.
517 */
518 if (error == 0 && batched && (vnode_mount(dvp) == vnode_mount(vp))) {
519 error = VNOP_COMPOUND_OPEN(dvp, &ndp->ni_vp, ndp, 0, fmode, NULL, NULL, ctx);
520
521 if (error == 0) {
522 vp = ndp->ni_vp;
523 need_vnop_open = FALSE;
524 } else if (error == EKEEPLOOKING) {
525 if ((ndp->ni_flag & NAMEI_CONTLOOKUP) == 0) {
526 panic("EKEEPLOOKING, but continue flag not set?");
527 }
528 goto continue_create_lookup;
529 }
530 }
531 vnode_put(dvp);
532 ndp->ni_dvp = NULLVP;
533
534 if (error) {
535 goto bad;
536 }
537
538 fmode &= ~O_CREAT;
539
540 /* Fall through */
541 }
542 } else {
543 /*
544 * Not O_CREAT
545 */
546 ndp->ni_cnd.cn_nameiop = LOOKUP;
547 /* Inherit USEDVP, vnode_open() supported flags only */
548 ndp->ni_cnd.cn_flags &= (USEDVP | NOCROSSMOUNT);
549 ndp->ni_cnd.cn_flags |= FOLLOW | LOCKLEAF | AUDITVNPATH1 | WANTPARENT;
550 #if NAMEDRSRCFORK
551 /* open calls are allowed for resource forks. */
552 ndp->ni_cnd.cn_flags |= CN_ALLOWRSRCFORK;
553 #endif
554 if (fmode & FENCRYPTED) {
555 ndp->ni_cnd.cn_flags |= CN_RAW_ENCRYPTED | CN_SKIPNAMECACHE;
556 }
557 /* Inherit NAMEI_ROOTDIR flag only */
558 ndp->ni_flag &= NAMEI_ROOTDIR;
559 ndp->ni_flag |= NAMEI_COMPOUNDOPEN;
560
561 /* preserve NOFOLLOW from vnode_open() */
562 if (fmode & O_NOFOLLOW || fmode & O_SYMLINK || (origcnflags & FOLLOW) == 0) {
563 ndp->ni_cnd.cn_flags &= ~FOLLOW;
564 }
565 if (fmode & O_NOFOLLOW_ANY) {
566 /* will return ELOOP on the first symlink to be hit */
567 ndp->ni_flag |= NAMEI_NOFOLLOW_ANY;
568 }
569
570 /* Do a lookup, possibly going directly to filesystem for compound operation */
571 do {
572 if ((error = namei(ndp))) {
573 goto out;
574 }
575 vp = ndp->ni_vp;
576 dvp = ndp->ni_dvp;
577
578 /* Check for batched lookup-open */
579 batched = vnode_compound_open_available(dvp);
580 if (batched && ((vp == NULLVP) || (vnode_mount(dvp) == vnode_mount(vp)))) {
581 error = VNOP_COMPOUND_OPEN(dvp, &ndp->ni_vp, ndp, 0, fmode, NULL, NULL, ctx);
582 vp = ndp->ni_vp;
583 if (error == 0) {
584 need_vnop_open = FALSE;
585 } else if (error == EKEEPLOOKING) {
586 if ((ndp->ni_flag & NAMEI_CONTLOOKUP) == 0) {
587 panic("EKEEPLOOKING, but continue flag not set?");
588 }
589 } else if ((fmode & (FREAD | FWRITE | FEXEC)) == FEXEC) {
590 /*
591 * Some file systems fail in vnop_open call with absense of
592 * both FREAD and FWRITE access modes. Retry the vnop_open
593 * call again with FREAD access mode added.
594 */
595 error = VNOP_COMPOUND_OPEN(dvp, &ndp->ni_vp, ndp, 0,
596 fmode | FREAD, NULL, NULL, ctx);
597 if (error == 0) {
598 vp = ndp->ni_vp;
599 need_vnop_open = FALSE;
600 }
601 }
602 }
603 } while (error == EKEEPLOOKING);
604
605 vnode_put(dvp);
606 ndp->ni_dvp = NULLVP;
607
608 if (error) {
609 goto bad;
610 }
611 }
612
613 /*
614 * By this point, dvp iocount is dropped and dvp pointer is cleared.
615 */
616 if (ndp->ni_dvp != NULLVP) {
617 panic("Haven't cleaned up adequately in vn_open_auth()");
618 }
619
620 /*
621 * Expect to use this code for filesystems without compound VNOPs, for the root
622 * of a filesystem, which can't be "looked up" in the sense of VNOP_LOOKUP(),
623 * and for shadow files, which do not live on the same filesystems as their "parents."
624 */
625 if (need_vnop_open) {
626 if (batched && !vnode_isvroot(vp) && !vnode_isnamedstream(vp)) {
627 panic("Why am I trying to use VNOP_OPEN() on anything other than the root or a named stream?");
628 }
629
630 if (!did_create) {
631 error = vn_authorize_open_existing(vp, &ndp->ni_cnd, fmode, ctx, NULL);
632 if (error) {
633 goto bad;
634 }
635 }
636
637 if (VATTR_IS_ACTIVE(vap, va_dataprotect_flags)) {
638 if (ISSET(vap->va_dataprotect_flags, VA_DP_RAWUNENCRYPTED)) {
639 /* Don't allow unencrypted io request from user space unless entitled */
640 boolean_t entitled = FALSE;
641 #if !SECURE_KERNEL
642 entitled = IOCurrentTaskHasEntitlement("com.apple.private.security.file-unencrypt-access");
643 #endif /* SECURE_KERNEL */
644 if (!entitled) {
645 error = EPERM;
646 goto bad;
647 }
648 fmode |= FUNENCRYPTED;
649 }
650
651 if (ISSET(vap->va_dataprotect_flags, VA_DP_AUTHENTICATE)) {
652 fsioc_auth_fs_t afs = { .authvp = authvp };
653
654 error = VNOP_IOCTL(vp, FSIOC_AUTH_FS, (caddr_t)&afs, 0, ctx);
655 if (error) {
656 goto bad;
657 }
658 }
659 }
660
661 error = VNOP_OPEN(vp, fmode, ctx);
662 if (error) {
663 /*
664 * Some file systems fail in vnop_open call with absense of both
665 * FREAD and FWRITE access modes. Retry the vnop_open call again
666 * with FREAD access mode added.
667 */
668 if ((fmode & (FREAD | FWRITE | FEXEC)) == FEXEC) {
669 error = VNOP_OPEN(vp, fmode | FREAD, ctx);
670 }
671 if (error) {
672 goto bad;
673 }
674 }
675 need_vnop_open = FALSE;
676 }
677
678 // if the vnode is tagged VOPENEVT and the current process
679 // has the P_CHECKOPENEVT flag set, then we or in the O_EVTONLY
680 // flag to the open mode so that this open won't count against
681 // the vnode when carbon delete() does a vnode_isinuse() to see
682 // if a file is currently in use. this allows spotlight
683 // importers to not interfere with carbon apps that depend on
684 // the no-delete-if-busy semantics of carbon delete().
685 //
686 if (!did_create && (vp->v_flag & VOPENEVT) && (current_proc()->p_flag & P_CHECKOPENEVT)) {
687 fmode |= O_EVTONLY;
688 }
689
690 /*
691 * Grab reference, etc.
692 */
693 error = vn_open_auth_finish(vp, fmode, ctx);
694 if (error) {
695 ref_failed = TRUE;
696 goto bad;
697 }
698
699 /* Compound VNOP open is responsible for doing the truncate */
700 if (batched || did_create) {
701 fmode &= ~O_TRUNC;
702 }
703
704 *fmodep = fmode;
705 nameidone(ndp);
706 return 0;
707
708 bad:
709 /* Opened either explicitly or by a batched create */
710 if (!need_vnop_open) {
711 VNOP_CLOSE(vp, fmode, ctx);
712 }
713
714 ndp->ni_vp = NULL;
715 if (vp) {
716 #if NAMEDRSRCFORK
717 /* Aggressively recycle shadow files if we error'd out during open() */
718 if ((vnode_isnamedstream(vp)) &&
719 (vp->v_parent != NULLVP) &&
720 (vnode_isshadow(vp))) {
721 vnode_recycle(vp);
722 }
723 #endif
724 vnode_put(vp);
725 /*
726 * Check for a race against unlink. We had a vnode
727 * but according to vnode_authorize or VNOP_OPEN it
728 * no longer exists.
729 *
730 * EREDRIVEOPEN: means that we were hit by the tty allocation race or NFSv4 open/create race.
731 */
732 if (((error == ENOENT) && (*fmodep & O_CREAT)) || (error == EREDRIVEOPEN) || ref_failed) {
733 /*
734 * We'll retry here but it may be possible that we get
735 * into a retry "spin" inside the kernel and not allow
736 * threads, which need to run in order for the retry
737 * loop to end, to run. An example is an open of a
738 * terminal which is getting revoked and we spin here
739 * without yielding becasue namei and VNOP_OPEN are
740 * successful but vnode_ref fails. The revoke needs
741 * threads with an iocount to run but if spin here we
742 * may possibly be blcoking other threads from running.
743 *
744 * We start yielding the CPU after some number of
745 * retries for increasing durations. Note that this is
746 * still a loop without an exit condition.
747 */
748 nretries += 1;
749 if (nretries > RETRY_NO_YIELD_COUNT) {
750 /* Every hz/100 secs is 10 msecs ... */
751 tsleep(&nretries, PVFS, "vn_open_auth_retry",
752 MIN((nretries * (hz / 100)), hz));
753 }
754 nameidone(ndp);
755 goto again;
756 }
757 }
758
759 out:
760 nameidone(ndp);
761 return error;
762 }
763
764 #if vn_access_DEPRECATED
765 /*
766 * Authorize an action against a vnode. This has been the canonical way to
767 * ensure that the credential/process/etc. referenced by a vfs_context
768 * is granted the rights called out in 'mode' against the vnode 'vp'.
769 *
770 * Unfortunately, the use of VREAD/VWRITE/VEXEC makes it very difficult
771 * to add support for more rights. As such, this interface will be deprecated
772 * and callers will use vnode_authorize instead.
773 */
774 int
vn_access(vnode_t vp,int mode,vfs_context_t context)775 vn_access(vnode_t vp, int mode, vfs_context_t context)
776 {
777 kauth_action_t action;
778
779 action = 0;
780 if (mode & VREAD) {
781 action |= KAUTH_VNODE_READ_DATA;
782 }
783 if (mode & VWRITE) {
784 action |= KAUTH_VNODE_WRITE_DATA;
785 }
786 if (mode & VEXEC) {
787 action |= KAUTH_VNODE_EXECUTE;
788 }
789
790 return vnode_authorize(vp, NULL, action, context);
791 }
792 #endif /* vn_access_DEPRECATED */
793
794 /*
795 * Vnode close call
796 */
797 int
vn_close(struct vnode * vp,int flags,vfs_context_t ctx)798 vn_close(struct vnode *vp, int flags, vfs_context_t ctx)
799 {
800 int error;
801 int flusherror = 0;
802
803 #if NAMEDRSRCFORK
804 /* Sync data from resource fork shadow file if needed. */
805 if ((vp->v_flag & VISNAMEDSTREAM) &&
806 (vp->v_parent != NULLVP) &&
807 vnode_isshadow(vp)) {
808 if (flags & FWASWRITTEN) {
809 flusherror = vnode_flushnamedstream(vp->v_parent, vp, ctx);
810 }
811 }
812 #endif
813 /*
814 * If vnode @vp belongs to a chardev or a blkdev then it is handled
815 * specially. We first drop its user reference count @vp->v_usecount
816 * before calling VNOP_CLOSE(). This was done historically to ensure
817 * that the last close of a special device vnode performed some
818 * conditional cleanups. Now we still need to drop this reference here
819 * to ensure that devfsspec_close() can check if the vnode is still in
820 * use.
821 */
822 if (vnode_isspec(vp)) {
823 (void)vnode_rele_ext(vp, flags, 0);
824 }
825
826 /*
827 * On HFS, we flush when the last writer closes. We do this
828 * because resource fork vnodes hold a reference on data fork
829 * vnodes and that will prevent them from getting VNOP_INACTIVE
830 * which will delay when we flush cached data. In future, we
831 * might find it beneficial to do this for all file systems.
832 * Note that it's OK to access v_writecount without the lock
833 * in this context.
834 */
835 if (vp->v_tag == VT_HFS && (flags & FWRITE) && vp->v_writecount == 1) {
836 VNOP_FSYNC(vp, MNT_NOWAIT, ctx);
837 }
838
839 error = VNOP_CLOSE(vp, flags, ctx);
840
841 #if CONFIG_FSE
842 if (flags & FWASWRITTEN) {
843 if (need_fsevent(FSE_CONTENT_MODIFIED, vp)) {
844 add_fsevent(FSE_CONTENT_MODIFIED, ctx,
845 FSE_ARG_VNODE, vp,
846 FSE_ARG_DONE);
847 }
848 }
849 #endif
850
851 if (!vnode_isspec(vp)) {
852 (void)vnode_rele_ext(vp, flags, 0);
853 }
854
855 if (flusherror) {
856 error = flusherror;
857 }
858 return error;
859 }
860
861 static int
vn_read_swapfile(struct vnode * vp,uio_t uio)862 vn_read_swapfile(
863 struct vnode *vp,
864 uio_t uio)
865 {
866 int error;
867 off_t swap_count, this_count;
868 off_t file_end, read_end;
869 off_t prev_resid;
870 char *my_swap_page;
871
872 /*
873 * Reading from a swap file will get you zeroes.
874 */
875
876 my_swap_page = NULL;
877 error = 0;
878 swap_count = uio_resid(uio);
879
880 file_end = ubc_getsize(vp);
881 read_end = uio->uio_offset + uio_resid(uio);
882 if (uio->uio_offset >= file_end) {
883 /* uio starts after end of file: nothing to read */
884 swap_count = 0;
885 } else if (read_end > file_end) {
886 /* uio extends beyond end of file: stop before that */
887 swap_count -= (read_end - file_end);
888 }
889
890 while (swap_count > 0) {
891 if (my_swap_page == NULL) {
892 my_swap_page = kalloc_data(PAGE_SIZE, Z_WAITOK | Z_ZERO);
893 /* add an end-of-line to keep line counters happy */
894 my_swap_page[PAGE_SIZE - 1] = '\n';
895 }
896 this_count = swap_count;
897 if (this_count > PAGE_SIZE) {
898 this_count = PAGE_SIZE;
899 }
900
901 prev_resid = uio_resid(uio);
902 error = uiomove((caddr_t) my_swap_page,
903 (int)this_count,
904 uio);
905 if (error) {
906 break;
907 }
908 swap_count -= (prev_resid - uio_resid(uio));
909 }
910 kfree_data(my_swap_page, PAGE_SIZE);
911
912 return error;
913 }
914 /*
915 * Package up an I/O request on a vnode into a uio and do it.
916 */
917 int
vn_rdwr(enum uio_rw rw,struct vnode * vp,caddr_t base,int len,off_t offset,enum uio_seg segflg,int ioflg,kauth_cred_t cred,int * aresid,proc_t p)918 vn_rdwr(
919 enum uio_rw rw,
920 struct vnode *vp,
921 caddr_t base,
922 int len,
923 off_t offset,
924 enum uio_seg segflg,
925 int ioflg,
926 kauth_cred_t cred,
927 int *aresid,
928 proc_t p)
929 {
930 int64_t resid;
931 int result;
932
933 if (len < 0) {
934 return EINVAL;
935 }
936
937 result = vn_rdwr_64(rw,
938 vp,
939 (uint64_t)(uintptr_t)base,
940 (int64_t)len,
941 offset,
942 segflg,
943 ioflg,
944 cred,
945 &resid,
946 p);
947
948 /* "resid" should be bounded above by "len," which is an int */
949 if (aresid != NULL) {
950 *aresid = (int)resid;
951 }
952
953 return result;
954 }
955
956
957 int
vn_rdwr_64(enum uio_rw rw,struct vnode * vp,uint64_t base,int64_t len,off_t offset,enum uio_seg segflg,int ioflg,kauth_cred_t cred,int64_t * aresid,proc_t p)958 vn_rdwr_64(
959 enum uio_rw rw,
960 struct vnode *vp,
961 uint64_t base,
962 int64_t len,
963 off_t offset,
964 enum uio_seg segflg,
965 int ioflg,
966 kauth_cred_t cred,
967 int64_t *aresid,
968 proc_t p)
969 {
970 uio_t auio;
971 int spacetype;
972 struct vfs_context context;
973 int error = 0;
974 UIO_STACKBUF(uio_buf, 1);
975
976 context.vc_thread = current_thread();
977 context.vc_ucred = cred;
978
979 if (UIO_SEG_IS_USER_SPACE(segflg)) {
980 spacetype = proc_is64bit(p) ? UIO_USERSPACE64 : UIO_USERSPACE32;
981 } else {
982 spacetype = UIO_SYSSPACE;
983 }
984
985 if (len < 0) {
986 return EINVAL;
987 }
988
989 auio = uio_createwithbuffer(1, offset, spacetype, rw,
990 &uio_buf[0], sizeof(uio_buf));
991 uio_addiov(auio, CAST_USER_ADDR_T(base), (user_size_t)len);
992
993 #if CONFIG_MACF
994 /* XXXMAC
995 * IO_NOAUTH should be re-examined.
996 * Likely that mediation should be performed in caller.
997 */
998 if ((ioflg & IO_NOAUTH) == 0) {
999 /* passed cred is fp->f_cred */
1000 if (rw == UIO_READ) {
1001 error = mac_vnode_check_read(&context, cred, vp);
1002 } else {
1003 error = mac_vnode_check_write(&context, cred, vp);
1004 }
1005 }
1006 #endif
1007
1008 if (error == 0) {
1009 if (rw == UIO_READ) {
1010 if (vnode_isswap(vp) && ((ioflg & IO_SWAP_DISPATCH) == 0)) {
1011 error = vn_read_swapfile(vp, auio);
1012 } else {
1013 error = VNOP_READ(vp, auio, ioflg, &context);
1014 }
1015 } else {
1016 error = VNOP_WRITE(vp, auio, ioflg, &context);
1017 }
1018 }
1019
1020 if (aresid) {
1021 *aresid = uio_resid(auio);
1022 assert(*aresid <= len);
1023 } else if (uio_resid(auio) && error == 0) {
1024 error = EIO;
1025 }
1026 return error;
1027 }
1028
1029 void
vn_offset_lock(struct fileglob * fg)1030 vn_offset_lock(struct fileglob *fg)
1031 {
1032 lck_mtx_lock_spin(&fg->fg_lock);
1033 while (fg->fg_lflags & FG_OFF_LOCKED) {
1034 fg->fg_lflags |= FG_OFF_LOCKWANT;
1035 msleep(&fg->fg_lflags, &fg->fg_lock, PVFS | PSPIN,
1036 "fg_offset_lock_wait", 0);
1037 }
1038 fg->fg_lflags |= FG_OFF_LOCKED;
1039 lck_mtx_unlock(&fg->fg_lock);
1040 }
1041
1042 void
vn_offset_unlock(struct fileglob * fg)1043 vn_offset_unlock(struct fileglob *fg)
1044 {
1045 int lock_wanted = 0;
1046
1047 lck_mtx_lock_spin(&fg->fg_lock);
1048 if (fg->fg_lflags & FG_OFF_LOCKWANT) {
1049 lock_wanted = 1;
1050 }
1051 fg->fg_lflags &= ~(FG_OFF_LOCKED | FG_OFF_LOCKWANT);
1052 lck_mtx_unlock(&fg->fg_lock);
1053 if (lock_wanted) {
1054 wakeup(&fg->fg_lflags);
1055 }
1056 }
1057
1058 static int
vn_read_common(vnode_t vp,struct uio * uio,int fflag,vfs_context_t ctx)1059 vn_read_common(vnode_t vp, struct uio *uio, int fflag, vfs_context_t ctx)
1060 {
1061 int error;
1062 int ioflag;
1063 off_t read_offset;
1064 user_ssize_t read_len;
1065 user_ssize_t adjusted_read_len;
1066 user_ssize_t clippedsize;
1067
1068 /* Caller has already validated read_len. */
1069 read_len = uio_resid(uio);
1070 assert(read_len >= 0 && read_len <= INT_MAX);
1071
1072 adjusted_read_len = read_len;
1073 clippedsize = 0;
1074
1075 #if CONFIG_MACF
1076 error = mac_vnode_check_read(ctx, vfs_context_ucred(ctx), vp);
1077 if (error) {
1078 return error;
1079 }
1080 #endif
1081
1082 /* This signals to VNOP handlers that this read came from a file table read */
1083 ioflag = IO_SYSCALL_DISPATCH;
1084
1085 if (fflag & FNONBLOCK) {
1086 ioflag |= IO_NDELAY;
1087 }
1088 if ((fflag & FNOCACHE) || vnode_isnocache(vp)) {
1089 ioflag |= IO_NOCACHE;
1090 }
1091 if (fflag & FENCRYPTED) {
1092 ioflag |= IO_ENCRYPTED;
1093 }
1094 if (fflag & FUNENCRYPTED) {
1095 ioflag |= IO_SKIP_ENCRYPTION;
1096 }
1097 if (fflag & O_EVTONLY) {
1098 ioflag |= IO_EVTONLY;
1099 }
1100 if (fflag & FNORDAHEAD) {
1101 ioflag |= IO_RAOFF;
1102 }
1103
1104 read_offset = uio_offset(uio);
1105 /* POSIX allows negative offsets for character devices. */
1106 if ((read_offset < 0) && (vnode_vtype(vp) != VCHR)) {
1107 error = EINVAL;
1108 goto error_out;
1109 }
1110
1111 if (read_offset == INT64_MAX) {
1112 /* can't read any more */
1113 error = 0;
1114 goto error_out;
1115 }
1116
1117 /*
1118 * If offset + len will cause overflow, reduce the len to a value
1119 * (adjusted_read_len) where it won't
1120 */
1121 if ((read_offset >= 0) && (INT64_MAX - read_offset) < read_len) {
1122 /*
1123 * 0 read_offset INT64_MAX
1124 * |-----------------------------------------------|----------|~~~
1125 * <--read_len-->
1126 * <-adjusted->
1127 */
1128 adjusted_read_len = (user_ssize_t)(INT64_MAX - read_offset);
1129 }
1130
1131 if (adjusted_read_len < read_len) {
1132 uio_setresid(uio, adjusted_read_len);
1133 clippedsize = read_len - adjusted_read_len;
1134 }
1135
1136 if (vnode_isswap(vp) && !(IO_SKIP_ENCRYPTION & ioflag)) {
1137 /* special case for swap files */
1138 error = vn_read_swapfile(vp, uio);
1139 } else {
1140 error = VNOP_READ(vp, uio, ioflag, ctx);
1141 }
1142
1143 if (clippedsize) {
1144 uio_setresid(uio, (uio_resid(uio) + clippedsize));
1145 }
1146
1147 error_out:
1148 return error;
1149 }
1150
1151 /*
1152 * File table vnode read routine.
1153 */
1154 static int
vn_read(struct fileproc * fp,struct uio * uio,int flags,vfs_context_t ctx)1155 vn_read(struct fileproc *fp, struct uio *uio, int flags, vfs_context_t ctx)
1156 {
1157 vnode_t vp;
1158 user_ssize_t read_len;
1159 int error;
1160 bool offset_locked;
1161
1162 read_len = uio_resid(uio);
1163 if (read_len < 0 || read_len > INT_MAX) {
1164 return EINVAL;
1165 }
1166
1167 if ((flags & FOF_OFFSET) == 0) {
1168 vn_offset_lock(fp->fp_glob);
1169 offset_locked = true;
1170 } else {
1171 offset_locked = false;
1172 }
1173 vp = (struct vnode *)fp_get_data(fp);
1174 if ((error = vnode_getwithref(vp))) {
1175 if (offset_locked) {
1176 vn_offset_unlock(fp->fp_glob);
1177 }
1178 return error;
1179 }
1180
1181 if (offset_locked && (vnode_vtype(vp) != VREG || vnode_isswap(vp))) {
1182 vn_offset_unlock(fp->fp_glob);
1183 offset_locked = false;
1184 }
1185
1186 if ((flags & FOF_OFFSET) == 0) {
1187 uio_setoffset(uio, fp->fp_glob->fg_offset);
1188 }
1189
1190 error = vn_read_common(vp, uio, fp->fp_glob->fg_flag, ctx);
1191
1192 if ((flags & FOF_OFFSET) == 0) {
1193 fp->fp_glob->fg_offset += read_len - uio_resid(uio);
1194 }
1195
1196 if (offset_locked) {
1197 vn_offset_unlock(fp->fp_glob);
1198 offset_locked = false;
1199 }
1200
1201 vnode_put(vp);
1202 return error;
1203 }
1204
1205 /*
1206 * File table vnode write routine.
1207 */
1208 static int
vn_write(struct fileproc * fp,struct uio * uio,int flags,vfs_context_t ctx)1209 vn_write(struct fileproc *fp, struct uio *uio, int flags, vfs_context_t ctx)
1210 {
1211 struct vnode *vp;
1212 int error, ioflag;
1213 off_t write_offset;
1214 off_t write_end_offset;
1215 user_ssize_t write_len;
1216 user_ssize_t adjusted_write_len;
1217 user_ssize_t clippedsize;
1218 bool offset_locked;
1219 proc_t p = vfs_context_proc(ctx);
1220 rlim_t rlim_cur_fsize = p ? proc_limitgetcur(p, RLIMIT_FSIZE) : 0;
1221
1222 write_len = uio_resid(uio);
1223 if (write_len < 0 || write_len > INT_MAX) {
1224 return EINVAL;
1225 }
1226 adjusted_write_len = write_len;
1227 clippedsize = 0;
1228
1229 if ((flags & FOF_OFFSET) == 0) {
1230 vn_offset_lock(fp->fp_glob);
1231 offset_locked = true;
1232 } else {
1233 offset_locked = false;
1234 }
1235
1236 vp = (struct vnode *)fp_get_data(fp);
1237 if ((error = vnode_getwithref(vp))) {
1238 if (offset_locked) {
1239 vn_offset_unlock(fp->fp_glob);
1240 }
1241 return error;
1242 }
1243
1244 if (offset_locked && (vnode_vtype(vp) != VREG || vnode_isswap(vp))) {
1245 vn_offset_unlock(fp->fp_glob);
1246 offset_locked = false;
1247 }
1248
1249 #if CONFIG_MACF
1250 error = mac_vnode_check_write(ctx, vfs_context_ucred(ctx), vp);
1251 if (error) {
1252 (void)vnode_put(vp);
1253 if (offset_locked) {
1254 vn_offset_unlock(fp->fp_glob);
1255 }
1256 return error;
1257 }
1258 #endif
1259
1260 /*
1261 * IO_SYSCALL_DISPATCH signals to VNOP handlers that this write came from
1262 * a file table write
1263 */
1264 ioflag = (IO_UNIT | IO_SYSCALL_DISPATCH);
1265
1266 if (vp->v_type == VREG && (fp->fp_glob->fg_flag & O_APPEND)) {
1267 ioflag |= IO_APPEND;
1268 }
1269 if (fp->fp_glob->fg_flag & FNONBLOCK) {
1270 ioflag |= IO_NDELAY;
1271 }
1272 assert(!(fp->fp_glob->fg_flag & O_NOCTTY) || (fp->fp_glob->fg_flag & FNOCACHE));
1273 if ((fp->fp_glob->fg_flag & FNOCACHE) || vnode_isnocache(vp)) {
1274 ioflag |= IO_NOCACHE;
1275 /*
1276 * O_NOCTTY is repurposed to indicate the preference for relaxed
1277 * alignment and size restrictions. O_NOCTTY has no meaning beyond
1278 * the open of the fd and is used only for ttys and the use
1279 * is mutually exclusive with nocache io for regular files.
1280 */
1281 if (fp->fp_glob->fg_flag & O_NOCTTY || vfs_context_allow_fs_blksize_nocache_write(ctx)) {
1282 ioflag |= IO_NOCACHE_SWRITE;
1283 }
1284 }
1285 if (fp->fp_glob->fg_flag & FNODIRECT) {
1286 ioflag |= IO_NODIRECT;
1287 }
1288 if (fp->fp_glob->fg_flag & FSINGLE_WRITER) {
1289 ioflag |= IO_SINGLE_WRITER;
1290 }
1291 if (fp->fp_glob->fg_flag & O_EVTONLY) {
1292 ioflag |= IO_EVTONLY;
1293 }
1294
1295 /*
1296 * Treat synchronous mounts and O_FSYNC on the fd as equivalent.
1297 *
1298 * XXX We treat O_DSYNC as O_FSYNC for now, since we can not delay
1299 * XXX the non-essential metadata without some additional VFS work;
1300 * XXX the intent at this point is to plumb the interface for it.
1301 */
1302 if ((fp->fp_glob->fg_flag & (O_FSYNC | O_DSYNC)) ||
1303 (vp->v_mount && (vp->v_mount->mnt_flag & MNT_SYNCHRONOUS))) {
1304 ioflag |= IO_SYNC;
1305 }
1306
1307 if ((flags & FOF_OFFSET) == 0) {
1308 write_offset = fp->fp_glob->fg_offset;
1309 uio_setoffset(uio, write_offset);
1310 } else {
1311 /* for pwrite, append should be ignored */
1312 ioflag &= ~IO_APPEND;
1313 write_offset = uio_offset(uio);
1314 /* POSIX allows negative offsets for character devices. */
1315 if ((write_offset < 0) && (vnode_vtype(vp) != VCHR)) {
1316 error = EINVAL;
1317 goto error_out;
1318 }
1319 }
1320
1321 if (write_offset == INT64_MAX) {
1322 /* writes are not possible */
1323 error = EFBIG;
1324 goto error_out;
1325 }
1326
1327 /*
1328 * write_len is the original write length that was requested.
1329 * We may however need to reduce that becasue of two reasons
1330 *
1331 * 1) If write_offset + write_len will exceed OFF_T_MAX (i.e. INT64_MAX)
1332 * and/or
1333 * 2) If write_offset + write_len will exceed the administrative
1334 * limit for the maximum file size.
1335 *
1336 * In both cases the write will be denied if we can't write even a single
1337 * byte otherwise it will be "clipped" (i.e. a short write).
1338 */
1339
1340 /*
1341 * If offset + len will cause overflow, reduce the len
1342 * to a value (adjusted_write_len) where it won't
1343 */
1344 if ((write_offset >= 0) && (INT64_MAX - write_offset) < write_len) {
1345 /*
1346 * 0 write_offset INT64_MAX
1347 * |-----------------------------------------------|----------|~~~
1348 * <--write_len-->
1349 * <-adjusted->
1350 */
1351 adjusted_write_len = (user_ssize_t)(INT64_MAX - write_offset);
1352 }
1353
1354 /* write_end_offset will always be [0, INT64_MAX] */
1355 write_end_offset = write_offset + adjusted_write_len;
1356
1357 if (p && (vp->v_type == VREG) &&
1358 (rlim_cur_fsize != RLIM_INFINITY) &&
1359 (rlim_cur_fsize <= INT64_MAX) &&
1360 (write_end_offset > (off_t)rlim_cur_fsize)) {
1361 /*
1362 * If the requested residual would cause us to go past the
1363 * administrative limit, then we need to adjust the residual
1364 * down to cause fewer bytes than requested to be written. If
1365 * we can't do that (e.g. the residual is already 1 byte),
1366 * then we fail the write with EFBIG.
1367 */
1368 if (write_offset >= (off_t)rlim_cur_fsize) {
1369 /*
1370 * 0 rlim_fsize write_offset write_end INT64_MAX
1371 * |------------------------|----------|-------------|--------|
1372 * <--write_len-->
1373 *
1374 * write not permitted
1375 */
1376 psignal(p, SIGXFSZ);
1377 error = EFBIG;
1378 goto error_out;
1379 }
1380
1381 /*
1382 * 0 write_offset rlim_fsize write_end INT64_MAX
1383 * |------------------------|-----------|---------|------------|
1384 * <------write_len------>
1385 * <-adjusted-->
1386 */
1387 adjusted_write_len = (user_ssize_t)((off_t)rlim_cur_fsize - write_offset);
1388 assert((adjusted_write_len > 0) && (adjusted_write_len < write_len));
1389 }
1390
1391 if (adjusted_write_len < write_len) {
1392 uio_setresid(uio, adjusted_write_len);
1393 clippedsize = write_len - adjusted_write_len;
1394 }
1395
1396 error = VNOP_WRITE(vp, uio, ioflag, ctx);
1397
1398 /*
1399 * If we had to reduce the size of write requested either because
1400 * of rlimit or because it would have exceeded
1401 * maximum file size, we have to add that back to the residual so
1402 * it correctly reflects what we did in this function.
1403 */
1404 if (clippedsize) {
1405 uio_setresid(uio, (uio_resid(uio) + clippedsize));
1406 }
1407
1408 if ((flags & FOF_OFFSET) == 0) {
1409 if (ioflag & IO_APPEND) {
1410 fp->fp_glob->fg_offset = uio_offset(uio);
1411 } else {
1412 fp->fp_glob->fg_offset += (write_len - uio_resid(uio));
1413 }
1414 if (offset_locked) {
1415 vn_offset_unlock(fp->fp_glob);
1416 offset_locked = false;
1417 }
1418 }
1419
1420 /*
1421 * Set the credentials on successful writes
1422 */
1423 if ((error == 0) && (vp->v_tag == VT_NFS) && (UBCINFOEXISTS(vp))) {
1424 ubc_setcred(vp, vfs_context_ucred(ctx));
1425 }
1426
1427 #if CONFIG_FILE_LEASES
1428 /*
1429 * On success, break the parent dir lease as the file's attributes (size
1430 * and/or mtime) have changed. Best attempt to break lease, just drop the
1431 * the error upon failure as there is no point to return error when the
1432 * write has completed successfully.
1433 */
1434 if (__probable(error == 0)) {
1435 vnode_breakdirlease(vp, true, O_WRONLY);
1436 }
1437 #endif /* CONFIG_FILE_LEASES */
1438
1439 (void)vnode_put(vp);
1440 return error;
1441
1442 error_out:
1443 if (offset_locked) {
1444 vn_offset_unlock(fp->fp_glob);
1445 }
1446 (void)vnode_put(vp);
1447 return error;
1448 }
1449
1450 /*
1451 * File table vnode stat routine.
1452 *
1453 * Returns: 0 Success
1454 * EBADF
1455 * ENOMEM
1456 * vnode_getattr:???
1457 */
1458 int
vn_stat_noauth(struct vnode * vp,void * sbptr,kauth_filesec_t * xsec,int isstat64,int needsrealdev,vfs_context_t ctx,struct ucred * file_cred)1459 vn_stat_noauth(struct vnode *vp, void *sbptr, kauth_filesec_t *xsec, int isstat64,
1460 int needsrealdev, vfs_context_t ctx, struct ucred *file_cred)
1461 {
1462 struct vnode_attr va;
1463 int error;
1464 u_short mode;
1465 kauth_filesec_t fsec;
1466 struct stat *sb = (struct stat *)0; /* warning avoidance ; protected by isstat64 */
1467 struct stat64 * sb64 = (struct stat64 *)0; /* warning avoidance ; protected by isstat64 */
1468
1469 if (isstat64 != 0) {
1470 sb64 = (struct stat64 *)sbptr;
1471 } else {
1472 sb = (struct stat *)sbptr;
1473 }
1474 memset(&va, 0, sizeof(va));
1475 VATTR_INIT(&va);
1476 VATTR_WANTED(&va, va_fsid);
1477 VATTR_WANTED(&va, va_fileid);
1478 VATTR_WANTED(&va, va_mode);
1479 VATTR_WANTED(&va, va_type);
1480 VATTR_WANTED(&va, va_nlink);
1481 VATTR_WANTED(&va, va_uid);
1482 VATTR_WANTED(&va, va_gid);
1483 VATTR_WANTED(&va, va_rdev);
1484 VATTR_WANTED(&va, va_data_size);
1485 VATTR_WANTED(&va, va_access_time);
1486 VATTR_WANTED(&va, va_modify_time);
1487 VATTR_WANTED(&va, va_change_time);
1488 VATTR_WANTED(&va, va_create_time);
1489 VATTR_WANTED(&va, va_flags);
1490 VATTR_WANTED(&va, va_gen);
1491 VATTR_WANTED(&va, va_iosize);
1492 /* lower layers will synthesise va_total_alloc from va_data_size if required */
1493 VATTR_WANTED(&va, va_total_alloc);
1494 if (xsec != NULL) {
1495 VATTR_WANTED(&va, va_uuuid);
1496 VATTR_WANTED(&va, va_guuid);
1497 VATTR_WANTED(&va, va_acl);
1498 }
1499 if (needsrealdev) {
1500 va.va_vaflags = VA_REALFSID;
1501 }
1502 error = vnode_getattr(vp, &va, ctx);
1503 if (error) {
1504 goto out;
1505 }
1506 #if CONFIG_MACF
1507 /*
1508 * Give MAC polices a chance to reject or filter the attributes
1509 * returned by the filesystem. Note that MAC policies are consulted
1510 * *after* calling the filesystem because filesystems can return more
1511 * attributes than were requested so policies wouldn't be authoritative
1512 * is consulted beforehand. This also gives policies an opportunity
1513 * to change the values of attributes retrieved.
1514 */
1515 error = mac_vnode_check_getattr(ctx, file_cred, vp, &va);
1516 if (error) {
1517 goto out;
1518 }
1519 #endif
1520 /*
1521 * Copy from vattr table
1522 */
1523 if (isstat64 != 0) {
1524 sb64->st_dev = va.va_fsid;
1525 sb64->st_ino = (ino64_t)va.va_fileid;
1526 } else {
1527 sb->st_dev = va.va_fsid;
1528 sb->st_ino = (ino_t)va.va_fileid;
1529 }
1530 mode = va.va_mode;
1531 switch (vp->v_type) {
1532 case VREG:
1533 mode |= S_IFREG;
1534 break;
1535 case VDIR:
1536 mode |= S_IFDIR;
1537 break;
1538 case VBLK:
1539 mode |= S_IFBLK;
1540 break;
1541 case VCHR:
1542 mode |= S_IFCHR;
1543 break;
1544 case VLNK:
1545 mode |= S_IFLNK;
1546 break;
1547 case VSOCK:
1548 mode |= S_IFSOCK;
1549 break;
1550 case VFIFO:
1551 mode |= S_IFIFO;
1552 break;
1553 default:
1554 error = EBADF;
1555 goto out;
1556 }
1557 ;
1558 if (isstat64 != 0) {
1559 sb64->st_mode = mode;
1560 sb64->st_nlink = VATTR_IS_SUPPORTED(&va, va_nlink) ? va.va_nlink > UINT16_MAX ? UINT16_MAX : (u_int16_t)va.va_nlink : 1;
1561 sb64->st_uid = va.va_uid;
1562 sb64->st_gid = va.va_gid;
1563 sb64->st_rdev = va.va_rdev;
1564 sb64->st_size = va.va_data_size;
1565 sb64->st_atimespec = va.va_access_time;
1566 sb64->st_mtimespec = va.va_modify_time;
1567 sb64->st_ctimespec = va.va_change_time;
1568 if (VATTR_IS_SUPPORTED(&va, va_create_time)) {
1569 sb64->st_birthtimespec = va.va_create_time;
1570 } else {
1571 sb64->st_birthtimespec.tv_sec = sb64->st_birthtimespec.tv_nsec = 0;
1572 }
1573 sb64->st_blksize = va.va_iosize;
1574 sb64->st_flags = va.va_flags;
1575 sb64->st_blocks = roundup(va.va_total_alloc, 512) / 512;
1576 } else {
1577 sb->st_mode = mode;
1578 sb->st_nlink = VATTR_IS_SUPPORTED(&va, va_nlink) ? va.va_nlink > UINT16_MAX ? UINT16_MAX : (u_int16_t)va.va_nlink : 1;
1579 sb->st_uid = va.va_uid;
1580 sb->st_gid = va.va_gid;
1581 sb->st_rdev = va.va_rdev;
1582 sb->st_size = va.va_data_size;
1583 sb->st_atimespec = va.va_access_time;
1584 sb->st_mtimespec = va.va_modify_time;
1585 sb->st_ctimespec = va.va_change_time;
1586 sb->st_blksize = va.va_iosize;
1587 sb->st_flags = va.va_flags;
1588 sb->st_blocks = roundup(va.va_total_alloc, 512) / 512;
1589 }
1590
1591 /* if we're interested in extended security data and we got an ACL */
1592 if (xsec != NULL) {
1593 if (!VATTR_IS_SUPPORTED(&va, va_acl) &&
1594 !VATTR_IS_SUPPORTED(&va, va_uuuid) &&
1595 !VATTR_IS_SUPPORTED(&va, va_guuid)) {
1596 *xsec = KAUTH_FILESEC_NONE;
1597 } else {
1598 if (VATTR_IS_SUPPORTED(&va, va_acl) && (va.va_acl != NULL)) {
1599 fsec = kauth_filesec_alloc(va.va_acl->acl_entrycount);
1600 } else {
1601 fsec = kauth_filesec_alloc(0);
1602 }
1603 if (fsec == NULL) {
1604 error = ENOMEM;
1605 goto out;
1606 }
1607 fsec->fsec_magic = KAUTH_FILESEC_MAGIC;
1608 if (VATTR_IS_SUPPORTED(&va, va_uuuid)) {
1609 fsec->fsec_owner = va.va_uuuid;
1610 } else {
1611 fsec->fsec_owner = kauth_null_guid;
1612 }
1613 if (VATTR_IS_SUPPORTED(&va, va_guuid)) {
1614 fsec->fsec_group = va.va_guuid;
1615 } else {
1616 fsec->fsec_group = kauth_null_guid;
1617 }
1618 if (VATTR_IS_SUPPORTED(&va, va_acl) && (va.va_acl != NULL)) {
1619 __nochk_bcopy(va.va_acl, &(fsec->fsec_acl), KAUTH_ACL_COPYSIZE(va.va_acl));
1620 } else {
1621 fsec->fsec_acl.acl_entrycount = KAUTH_FILESEC_NOACL;
1622 }
1623 *xsec = fsec;
1624 }
1625 }
1626
1627 /* Do not give the generation number out to unpriviledged users */
1628 if (va.va_gen && !vfs_context_issuser(ctx)) {
1629 if (isstat64 != 0) {
1630 sb64->st_gen = 0;
1631 } else {
1632 sb->st_gen = 0;
1633 }
1634 } else {
1635 if (isstat64 != 0) {
1636 sb64->st_gen = va.va_gen;
1637 } else {
1638 sb->st_gen = va.va_gen;
1639 }
1640 }
1641
1642 error = 0;
1643 out:
1644 if (VATTR_IS_SUPPORTED(&va, va_acl) && va.va_acl != NULL) {
1645 kauth_acl_free(va.va_acl);
1646 }
1647 return error;
1648 }
1649
1650 int
vn_stat(struct vnode * vp,void * sb,kauth_filesec_t * xsec,int isstat64,int needsrealdev,vfs_context_t ctx)1651 vn_stat(struct vnode *vp, void *sb, kauth_filesec_t *xsec, int isstat64, int needsrealdev, vfs_context_t ctx)
1652 {
1653 int error;
1654
1655 #if CONFIG_MACF
1656 error = mac_vnode_check_stat(ctx, NOCRED, vp);
1657 if (error) {
1658 return error;
1659 }
1660 #endif
1661
1662 /* authorize */
1663 if ((error = vnode_authorize(vp, NULL, KAUTH_VNODE_READ_ATTRIBUTES | KAUTH_VNODE_READ_SECURITY, ctx)) != 0) {
1664 return error;
1665 }
1666
1667 /* actual stat */
1668 return vn_stat_noauth(vp, sb, xsec, isstat64, needsrealdev, ctx, NOCRED);
1669 }
1670
1671
1672 /*
1673 * File table vnode ioctl routine.
1674 */
1675 static int
vn_ioctl(struct fileproc * fp,u_long com,caddr_t data,vfs_context_t ctx)1676 vn_ioctl(struct fileproc *fp, u_long com, caddr_t data, vfs_context_t ctx)
1677 {
1678 struct vnode *vp = (struct vnode *)fp_get_data(fp);
1679 off_t file_size;
1680 int error;
1681 struct vnode *ttyvp;
1682
1683 if ((error = vnode_getwithref(vp))) {
1684 return error;
1685 }
1686
1687 #if CONFIG_MACF
1688 error = mac_vnode_check_ioctl(ctx, vp, com);
1689 if (error) {
1690 goto out;
1691 }
1692 #endif
1693
1694 switch (vp->v_type) {
1695 case VREG:
1696 case VDIR:
1697 if (com == FIONREAD) {
1698 off_t temp_nbytes;
1699 if ((error = vnode_size(vp, &file_size, ctx)) != 0) {
1700 goto out;
1701 }
1702 temp_nbytes = file_size - fp->fp_glob->fg_offset;
1703 if (temp_nbytes > INT_MAX) {
1704 *(int *)data = INT_MAX;
1705 } else if (temp_nbytes < 0) {
1706 *(int *)data = 0;
1707 } else {
1708 *(int *)data = (int)temp_nbytes;
1709 }
1710 goto out;
1711 }
1712 if (com == FIONBIO || com == FIOASYNC) { /* XXX */
1713 goto out;
1714 }
1715 OS_FALLTHROUGH;
1716
1717 default:
1718 error = ENOTTY;
1719 goto out;
1720
1721 case VFIFO:
1722 case VCHR:
1723 case VBLK:
1724
1725 if (com == TIOCREVOKE || com == TIOCREVOKECLEAR) {
1726 error = ENOTTY;
1727 goto out;
1728 }
1729
1730 /* Should not be able to set block size from user space */
1731 if (com == DKIOCSETBLOCKSIZE) {
1732 error = EPERM;
1733 goto out;
1734 }
1735
1736 /* Should not be able to check if filesystem is authenticated from user space */
1737 if (com == FSIOC_AUTH_FS) {
1738 error = ENOTTY;
1739 goto out;
1740 }
1741
1742 if (com == FIODTYPE) {
1743 if (vp->v_type == VBLK) {
1744 if (major(vp->v_rdev) >= nblkdev) {
1745 error = ENXIO;
1746 goto out;
1747 }
1748 *(int *)data = bdevsw[major(vp->v_rdev)].d_type;
1749 } else if (vp->v_type == VCHR) {
1750 if (major(vp->v_rdev) >= nchrdev) {
1751 error = ENXIO;
1752 goto out;
1753 }
1754 *(int *)data = cdevsw[major(vp->v_rdev)].d_type;
1755 } else {
1756 error = ENOTTY;
1757 goto out;
1758 }
1759 goto out;
1760 }
1761 error = VNOP_IOCTL(vp, com, data, fp->fp_glob->fg_flag, ctx);
1762
1763 if (error == 0 && com == TIOCSCTTY) {
1764 struct session *sessp;
1765 struct pgrp *pg;
1766
1767 pg = proc_pgrp(vfs_context_proc(ctx), &sessp);
1768
1769 session_lock(sessp);
1770 ttyvp = sessp->s_ttyvp;
1771 sessp->s_ttyvp = vp;
1772 sessp->s_ttyvid = vnode_vid(vp);
1773 session_unlock(sessp);
1774
1775 pgrp_rele(pg);
1776 }
1777 }
1778 out:
1779 (void)vnode_put(vp);
1780 return error;
1781 }
1782
1783 /*
1784 * File table vnode select routine.
1785 */
1786 static int
vn_select(struct fileproc * fp,int which,void * wql,__unused vfs_context_t ctx)1787 vn_select(struct fileproc *fp, int which, void *wql, __unused vfs_context_t ctx)
1788 {
1789 int error;
1790 struct vnode * vp = (struct vnode *)fp_get_data(fp);
1791 struct vfs_context context;
1792
1793 if ((error = vnode_getwithref(vp)) == 0) {
1794 context.vc_thread = current_thread();
1795 context.vc_ucred = fp->fp_glob->fg_cred;
1796
1797 #if CONFIG_MACF
1798 /*
1799 * XXX We should use a per thread credential here; minimally,
1800 * XXX the process credential should have a persistent
1801 * XXX reference on it before being passed in here.
1802 */
1803 error = mac_vnode_check_select(ctx, vp, which);
1804 if (error == 0)
1805 #endif
1806 error = VNOP_SELECT(vp, which, fp->fp_glob->fg_flag, wql, ctx);
1807
1808 (void)vnode_put(vp);
1809 }
1810 return error;
1811 }
1812
1813 /*
1814 * File table vnode close routine.
1815 */
1816 static int
vn_closefile(struct fileglob * fg,vfs_context_t ctx)1817 vn_closefile(struct fileglob *fg, vfs_context_t ctx)
1818 {
1819 struct vnode *vp = fg_get_data(fg);
1820 int error;
1821
1822 if ((error = vnode_getwithref(vp)) == 0) {
1823 if (FILEGLOB_DTYPE(fg) == DTYPE_VNODE &&
1824 ((fg->fg_flag & FWASLOCKED) != 0 ||
1825 (fg->fg_lflags & FG_HAS_OFDLOCK) != 0)) {
1826 struct flock lf = {
1827 .l_whence = SEEK_SET,
1828 .l_start = 0,
1829 .l_len = 0,
1830 .l_type = F_UNLCK
1831 };
1832
1833 if ((fg->fg_flag & FWASLOCKED) != 0) {
1834 (void) VNOP_ADVLOCK(vp, (caddr_t)fg,
1835 F_UNLCK, &lf, F_FLOCK, ctx, NULL);
1836 }
1837
1838 if ((fg->fg_lflags & FG_HAS_OFDLOCK) != 0) {
1839 (void) VNOP_ADVLOCK(vp, ofd_to_id(fg),
1840 F_UNLCK, &lf, F_OFD_LOCK, ctx, NULL);
1841 }
1842 }
1843 #if CONFIG_FILE_LEASES
1844 if (FILEGLOB_DTYPE(fg) == DTYPE_VNODE && !LIST_EMPTY(&vp->v_leases)) {
1845 /* Expected open count doesn't matter for release. */
1846 (void)vnode_setlease(vp, fg, F_UNLCK, 0, ctx);
1847 }
1848 #endif
1849 error = vn_close(vp, fg->fg_flag, ctx);
1850 (void) vnode_put(vp);
1851 }
1852 return error;
1853 }
1854
1855 /*
1856 * Returns: 0 Success
1857 * VNOP_PATHCONF:???
1858 */
1859 int
vn_pathconf(vnode_t vp,int name,int32_t * retval,vfs_context_t ctx)1860 vn_pathconf(vnode_t vp, int name, int32_t *retval, vfs_context_t ctx)
1861 {
1862 int error = 0;
1863 struct vfs_attr vfa;
1864
1865 switch (name) {
1866 case _PC_EXTENDED_SECURITY_NP:
1867 *retval = vfs_extendedsecurity(vnode_mount(vp)) ? 1 : 0;
1868 break;
1869 case _PC_AUTH_OPAQUE_NP:
1870 *retval = vfs_authopaque(vnode_mount(vp));
1871 break;
1872 case _PC_2_SYMLINKS:
1873 *retval = 1; /* XXX NOTSUP on MSDOS, etc. */
1874 break;
1875 case _PC_ALLOC_SIZE_MIN:
1876 *retval = 1; /* XXX lie: 1 byte */
1877 break;
1878 case _PC_ASYNC_IO: /* unistd.h: _POSIX_ASYNCHRONUS_IO */
1879 *retval = 1; /* [AIO] option is supported */
1880 break;
1881 case _PC_PRIO_IO: /* unistd.h: _POSIX_PRIORITIZED_IO */
1882 *retval = 0; /* [PIO] option is not supported */
1883 break;
1884 case _PC_REC_INCR_XFER_SIZE:
1885 *retval = 4096; /* XXX go from MIN to MAX 4K at a time */
1886 break;
1887 case _PC_REC_MIN_XFER_SIZE:
1888 *retval = 4096; /* XXX recommend 4K minimum reads/writes */
1889 break;
1890 case _PC_REC_MAX_XFER_SIZE:
1891 *retval = 65536; /* XXX recommend 64K maximum reads/writes */
1892 break;
1893 case _PC_REC_XFER_ALIGN:
1894 *retval = 4096; /* XXX recommend page aligned buffers */
1895 break;
1896 case _PC_SYMLINK_MAX:
1897 *retval = 255; /* Minimum acceptable POSIX value */
1898 break;
1899 case _PC_SYNC_IO: /* unistd.h: _POSIX_SYNCHRONIZED_IO */
1900 *retval = 0; /* [SIO] option is not supported */
1901 break;
1902 case _PC_XATTR_SIZE_BITS:
1903 /* The number of bits used to store maximum extended
1904 * attribute size in bytes. For example, if the maximum
1905 * attribute size supported by a file system is 128K, the
1906 * value returned will be 18. However a value 18 can mean
1907 * that the maximum attribute size can be anywhere from
1908 * (256KB - 1) to 128KB. As a special case, the resource
1909 * fork can have much larger size, and some file system
1910 * specific extended attributes can have smaller and preset
1911 * size; for example, Finder Info is always 32 bytes.
1912 */
1913 memset(&vfa, 0, sizeof(vfa));
1914 VFSATTR_INIT(&vfa);
1915 VFSATTR_WANTED(&vfa, f_capabilities);
1916 if (vfs_getattr(vnode_mount(vp), &vfa, ctx) == 0 &&
1917 (VFSATTR_IS_SUPPORTED(&vfa, f_capabilities)) &&
1918 (vfa.f_capabilities.capabilities[VOL_CAPABILITIES_INTERFACES] & VOL_CAP_INT_EXTENDED_ATTR) &&
1919 (vfa.f_capabilities.valid[VOL_CAPABILITIES_INTERFACES] & VOL_CAP_INT_EXTENDED_ATTR)) {
1920 /* Supports native extended attributes */
1921 error = VNOP_PATHCONF(vp, name, retval, ctx);
1922 } else {
1923 /* Number of bits used to represent the maximum size of
1924 * extended attribute stored in an Apple Double file.
1925 */
1926 *retval = AD_XATTR_SIZE_BITS;
1927 }
1928 break;
1929 default:
1930 error = VNOP_PATHCONF(vp, name, retval, ctx);
1931 break;
1932 }
1933
1934 return error;
1935 }
1936
1937 static int
vn_kqfilter(struct fileproc * fp,struct knote * kn,struct kevent_qos_s * kev)1938 vn_kqfilter(struct fileproc *fp, struct knote *kn, struct kevent_qos_s *kev)
1939 {
1940 vfs_context_t ctx = vfs_context_current();
1941 struct vnode *vp;
1942 int error = 0;
1943 int result = 0;
1944
1945 vp = (struct vnode *)fp_get_data(fp);
1946
1947 /*
1948 * Don't attach a knote to a dead vnode.
1949 */
1950 if ((error = vget_internal(vp, 0, VNODE_NODEAD)) == 0) {
1951 switch (kn->kn_filter) {
1952 case EVFILT_READ:
1953 case EVFILT_WRITE:
1954 if (vnode_isfifo(vp)) {
1955 /* We'll only watch FIFOs that use our fifofs */
1956 if (!(vp->v_fifoinfo && vp->v_fifoinfo->fi_readsock)) {
1957 error = ENOTSUP;
1958 }
1959 } else if (!vnode_isreg(vp)) {
1960 if (vnode_ischr(vp)) {
1961 result = spec_kqfilter(vp, kn, kev);
1962 if ((kn->kn_flags & EV_ERROR) == 0) {
1963 /* claimed by a special device */
1964 vnode_put(vp);
1965 return result;
1966 }
1967 }
1968 error = EINVAL;
1969 }
1970 break;
1971 case EVFILT_VNODE:
1972 break;
1973 default:
1974 error = EINVAL;
1975 }
1976
1977 if (error == 0) {
1978 #if CONFIG_MACF
1979 error = mac_vnode_check_kqfilter(ctx, fp->fp_glob->fg_cred, kn, vp);
1980 if (error) {
1981 vnode_put(vp);
1982 goto out;
1983 }
1984 #endif
1985
1986 kn->kn_filtid = EVFILTID_VN;
1987 knote_kn_hook_set_raw(kn, (void *)vp);
1988 vnode_hold(vp);
1989
1990 vnode_lock(vp);
1991 KNOTE_ATTACH(&vp->v_knotes, kn);
1992 result = filt_vnode_common(kn, NULL, vp, 0);
1993 vnode_unlock(vp);
1994
1995 /*
1996 * Ask the filesystem to provide remove notifications,
1997 * but ignore failure
1998 */
1999 VNOP_MONITOR(vp, 0, VNODE_MONITOR_BEGIN, (void*) kn, ctx);
2000 }
2001
2002 vnode_put(vp);
2003 }
2004
2005 out:
2006 if (error) {
2007 knote_set_error(kn, error);
2008 }
2009
2010 return result;
2011 }
2012
2013 static void
filt_vndetach(struct knote * kn)2014 filt_vndetach(struct knote *kn)
2015 {
2016 vfs_context_t ctx = vfs_context_current();
2017 struct vnode *vp = (struct vnode *)knote_kn_hook_get_raw(kn);
2018 uint32_t vid = vnode_vid(vp);
2019 if (vnode_getwithvid(vp, vid)) {
2020 vnode_drop(vp);
2021 return;
2022 }
2023 vnode_drop(vp);
2024
2025 vnode_lock(vp);
2026 KNOTE_DETACH(&vp->v_knotes, kn);
2027 vnode_unlock(vp);
2028
2029 /*
2030 * Tell a (generally networked) filesystem that we're no longer watching
2031 * If the FS wants to track contexts, it should still be using the one from
2032 * the VNODE_MONITOR_BEGIN.
2033 */
2034 VNOP_MONITOR(vp, 0, VNODE_MONITOR_END, (void*)kn, ctx);
2035 vnode_put(vp);
2036 }
2037
2038
2039 /*
2040 * Used for EVFILT_READ
2041 *
2042 * Takes only VFIFO or VREG. vnode is locked. We handle the "poll" case
2043 * differently than the regular case for VREG files. If not in poll(),
2044 * then we need to know current fileproc offset for VREG.
2045 */
2046 static int64_t
vnode_readable_data_count(vnode_t vp,off_t current_offset,int ispoll)2047 vnode_readable_data_count(vnode_t vp, off_t current_offset, int ispoll)
2048 {
2049 if (vnode_isfifo(vp)) {
2050 #if FIFO
2051 int cnt;
2052 int err = fifo_charcount(vp, &cnt);
2053 if (err == 0) {
2054 return (int64_t)cnt;
2055 } else
2056 #endif
2057 {
2058 return 0;
2059 }
2060 } else if (vnode_isreg(vp)) {
2061 if (ispoll) {
2062 return 1;
2063 }
2064
2065 off_t amount;
2066 amount = vp->v_un.vu_ubcinfo->ui_size - current_offset;
2067 if (amount > INT64_MAX) {
2068 return INT64_MAX;
2069 } else if (amount < INT64_MIN) {
2070 return INT64_MIN;
2071 } else {
2072 return (int64_t)amount;
2073 }
2074 } else {
2075 panic("Should never have an EVFILT_READ except for reg or fifo.");
2076 return 0;
2077 }
2078 }
2079
2080 /*
2081 * Used for EVFILT_WRITE.
2082 *
2083 * For regular vnodes, we can always write (1). For named pipes,
2084 * see how much space there is in the buffer. Nothing else is covered.
2085 */
2086 static intptr_t
vnode_writable_space_count(vnode_t vp)2087 vnode_writable_space_count(vnode_t vp)
2088 {
2089 if (vnode_isfifo(vp)) {
2090 #if FIFO
2091 long spc;
2092 int err = fifo_freespace(vp, &spc);
2093 if (err == 0) {
2094 return (intptr_t)spc;
2095 } else
2096 #endif
2097 {
2098 return (intptr_t)0;
2099 }
2100 } else if (vnode_isreg(vp)) {
2101 return (intptr_t)1;
2102 } else {
2103 panic("Should never have an EVFILT_READ except for reg or fifo.");
2104 return 0;
2105 }
2106 }
2107
2108 /*
2109 * Determine whether this knote should be active
2110 *
2111 * This is kind of subtle.
2112 * --First, notice if the vnode has been revoked: in so, override hint
2113 * --EVFILT_READ knotes are checked no matter what the hint is
2114 * --Other knotes activate based on hint.
2115 * --If hint is revoke, set special flags and activate
2116 */
2117 static int
filt_vnode_common(struct knote * kn,struct kevent_qos_s * kev,vnode_t vp,long hint)2118 filt_vnode_common(struct knote *kn, struct kevent_qos_s *kev, vnode_t vp, long hint)
2119 {
2120 int activate = 0;
2121 int64_t data = 0;
2122
2123 lck_mtx_assert(&vp->v_lock, LCK_MTX_ASSERT_OWNED);
2124
2125 /* Special handling for vnodes that are in recycle or already gone */
2126 if (NOTE_REVOKE == hint) {
2127 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
2128 activate = 1;
2129
2130 if ((kn->kn_filter == EVFILT_VNODE) && (kn->kn_sfflags & NOTE_REVOKE)) {
2131 kn->kn_fflags |= NOTE_REVOKE;
2132 }
2133 } else {
2134 switch (kn->kn_filter) {
2135 case EVFILT_READ:
2136 data = vnode_readable_data_count(vp, kn->kn_fp->fp_glob->fg_offset, (kn->kn_flags & EV_POLL));
2137 activate = (data != 0);
2138 break;
2139 case EVFILT_WRITE:
2140 data = vnode_writable_space_count(vp);
2141 activate = (data != 0);
2142 break;
2143 case EVFILT_VNODE:
2144 /* Check events this note matches against the hint */
2145 if (kn->kn_sfflags & hint) {
2146 kn->kn_fflags |= (uint32_t)hint; /* Set which event occurred */
2147 }
2148 activate = (kn->kn_fflags != 0);
2149 break;
2150 default:
2151 panic("Invalid knote filter on a vnode!");
2152 }
2153 }
2154
2155 if (kev && activate) {
2156 knote_fill_kevent(kn, kev, data);
2157 }
2158
2159 return activate;
2160 }
2161
2162 static int
filt_vnode(struct knote * kn,long hint)2163 filt_vnode(struct knote *kn, long hint)
2164 {
2165 vnode_t vp = (struct vnode *)knote_kn_hook_get_raw(kn);
2166
2167 return filt_vnode_common(kn, NULL, vp, hint);
2168 }
2169
2170 static int
filt_vntouch(struct knote * kn,struct kevent_qos_s * kev)2171 filt_vntouch(struct knote *kn, struct kevent_qos_s *kev)
2172 {
2173 vnode_t vp = (struct vnode *)knote_kn_hook_get_raw(kn);
2174 uint32_t vid = vnode_vid(vp);
2175 int activate;
2176 int hint = 0;
2177
2178 vnode_lock(vp);
2179 if (vnode_getiocount(vp, vid, VNODE_NODEAD | VNODE_WITHID) != 0) {
2180 /* is recycled */
2181 hint = NOTE_REVOKE;
2182 }
2183
2184 /* accept new input fflags mask */
2185 kn->kn_sfflags = kev->fflags;
2186
2187 activate = filt_vnode_common(kn, NULL, vp, hint);
2188
2189 if (hint == 0) {
2190 vnode_put_locked(vp);
2191 }
2192 vnode_unlock(vp);
2193
2194 return activate;
2195 }
2196
2197 static int
filt_vnprocess(struct knote * kn,struct kevent_qos_s * kev)2198 filt_vnprocess(struct knote *kn, struct kevent_qos_s *kev)
2199 {
2200 vnode_t vp = (struct vnode *)knote_kn_hook_get_raw(kn);
2201 uint32_t vid = vnode_vid(vp);
2202 int activate;
2203 int hint = 0;
2204
2205 vnode_lock(vp);
2206 if (vnode_getiocount(vp, vid, VNODE_NODEAD | VNODE_WITHID) != 0) {
2207 /* Is recycled */
2208 hint = NOTE_REVOKE;
2209 }
2210 activate = filt_vnode_common(kn, kev, vp, hint);
2211
2212 /* Definitely need to unlock, may need to put */
2213 if (hint == 0) {
2214 vnode_put_locked(vp);
2215 }
2216 vnode_unlock(vp);
2217
2218 return activate;
2219 }
2220
2221 struct vniodesc {
2222 vnode_t vnio_vnode; /* associated vnode */
2223 int vnio_fflags; /* cached fileglob flags */
2224 };
2225
2226 errno_t
vnio_openfd(int fd,vniodesc_t * vniop)2227 vnio_openfd(int fd, vniodesc_t *vniop)
2228 {
2229 proc_t p = current_proc();
2230 struct fileproc *fp = NULL;
2231 vniodesc_t vnio;
2232 vnode_t vp;
2233 int error;
2234 bool need_drop = false;
2235
2236 vnio = kalloc_type(struct vniodesc, Z_WAITOK);
2237
2238 error = fp_getfvp(p, fd, &fp, &vp);
2239 if (error) {
2240 goto out;
2241 }
2242 need_drop = true;
2243
2244 if ((fp->fp_glob->fg_flag & (FREAD | FWRITE)) == 0) {
2245 error = EBADF;
2246 goto out;
2247 }
2248
2249 if (vnode_isswap(vp)) {
2250 error = EPERM;
2251 goto out;
2252 }
2253
2254 if (vp->v_type != VREG) {
2255 error = EFTYPE;
2256 goto out;
2257 }
2258
2259 error = vnode_getwithref(vp);
2260 if (error) {
2261 goto out;
2262 }
2263
2264 vnio->vnio_vnode = vp;
2265 vnio->vnio_fflags = fp->fp_glob->fg_flag;
2266
2267 (void)fp_drop(p, fd, fp, 0);
2268 need_drop = false;
2269
2270 error = vnode_ref_ext(vp, vnio->vnio_fflags, 0);
2271 if (error == 0) {
2272 *vniop = vnio;
2273 vnio = NULL;
2274 }
2275
2276 vnode_put(vp);
2277
2278 out:
2279 if (need_drop) {
2280 fp_drop(p, fd, fp, 0);
2281 }
2282 if (vnio != NULL) {
2283 kfree_type(struct vniodesc, vnio);
2284 }
2285 return error;
2286 }
2287
2288 errno_t
vnio_close(vniodesc_t vnio)2289 vnio_close(vniodesc_t vnio)
2290 {
2291 int error;
2292
2293 /*
2294 * The vniodesc is always destroyed, because the close
2295 * always "succeeds". We just return whatever error
2296 * might have been encountered while doing so.
2297 */
2298
2299 error = vnode_getwithref(vnio->vnio_vnode);
2300 if (error == 0) {
2301 error = vnode_close(vnio->vnio_vnode, vnio->vnio_fflags, NULL);
2302 }
2303
2304 kfree_type(struct vniodesc, vnio);
2305
2306 return error;
2307 }
2308
2309 errno_t
vnio_read(vniodesc_t vnio,uio_t uio)2310 vnio_read(vniodesc_t vnio, uio_t uio)
2311 {
2312 vnode_t vp = vnio->vnio_vnode;
2313 user_ssize_t read_len;
2314 int error;
2315
2316 read_len = uio_resid(uio);
2317 if (read_len < 0 || read_len > INT_MAX) {
2318 return EINVAL;
2319 }
2320
2321 error = vnode_getwithref(vp);
2322 if (error == 0) {
2323 error = vn_read_common(vp, uio, vnio->vnio_fflags,
2324 vfs_context_current());
2325 vnode_put(vp);
2326 }
2327
2328 return error;
2329 }
2330
2331 vnode_t
vnio_vnode(vniodesc_t vnio)2332 vnio_vnode(vniodesc_t vnio)
2333 {
2334 return vnio->vnio_vnode;
2335 }
2336
2337 int
vnode_isauthfs(vnode_t vp)2338 vnode_isauthfs(vnode_t vp)
2339 {
2340 fsioc_auth_fs_t afs = { .authvp = NULL };
2341 int error;
2342
2343 error = VNOP_IOCTL(vp, FSIOC_AUTH_FS, (caddr_t)&afs, 0,
2344 vfs_context_current());
2345
2346 return error == 0 ? 1 : 0;
2347 }
2348