]> git.saurik.com Git - apple/xnu.git/blob - bsd/vfs/vfs_vnops.c
xnu-3789.1.32.tar.gz
[apple/xnu.git] / bsd / vfs / vfs_vnops.c
1 /*
2 * Copyright (c) 2000-2014 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/tty.h>
89 /* Temporary workaround for ubc.h until <rdar://4714366 is resolved */
90 #define ubc_setcred ubc_setcred_deprecated
91 #include <sys/ubc.h>
92 #undef ubc_setcred
93 int ubc_setcred(struct vnode *, struct proc *);
94 #include <sys/conf.h>
95 #include <sys/disk.h>
96 #include <sys/fsevents.h>
97 #include <sys/kdebug.h>
98 #include <sys/xattr.h>
99 #include <sys/ubc_internal.h>
100 #include <sys/uio_internal.h>
101 #include <sys/resourcevar.h>
102 #include <sys/signalvar.h>
103
104 #include <vm/vm_kern.h>
105 #include <vm/vm_map.h>
106
107 #include <miscfs/specfs/specdev.h>
108 #include <miscfs/fifofs/fifo.h>
109
110 #if CONFIG_MACF
111 #include <security/mac_framework.h>
112 #endif
113
114 #include <IOKit/IOBSD.h>
115
116 static int vn_closefile(struct fileglob *fp, vfs_context_t ctx);
117 static int vn_ioctl(struct fileproc *fp, u_long com, caddr_t data,
118 vfs_context_t ctx);
119 static int vn_read(struct fileproc *fp, struct uio *uio, int flags,
120 vfs_context_t ctx);
121 static int vn_write(struct fileproc *fp, struct uio *uio, int flags,
122 vfs_context_t ctx);
123 static int vn_select( struct fileproc *fp, int which, void * wql,
124 vfs_context_t ctx);
125 static int vn_kqfilt_add(struct fileproc *fp, struct knote *kn,
126 vfs_context_t ctx);
127 static void filt_vndetach(struct knote *kn);
128 static int filt_vnode(struct knote *kn, long hint);
129 static int filt_vnode_common(struct knote *kn, vnode_t vp, long hint);
130 static int vn_open_auth_finish(vnode_t vp, int fmode, vfs_context_t ctx);
131 #if 0
132 static int vn_kqfilt_remove(struct vnode *vp, uintptr_t ident,
133 vfs_context_t ctx);
134 #endif
135
136 const struct fileops vnops = {
137 .fo_type = DTYPE_VNODE,
138 .fo_read = vn_read,
139 .fo_write = vn_write,
140 .fo_ioctl = vn_ioctl,
141 .fo_select = vn_select,
142 .fo_close = vn_closefile,
143 .fo_kqfilter = vn_kqfilt_add,
144 .fo_drain = NULL,
145 };
146
147 static int filt_vntouch(struct knote *kn, struct kevent_internal_s *kev);
148 static int filt_vnprocess(struct knote *kn, struct filt_process_s *data, struct kevent_internal_s *kev);
149
150 struct filterops vnode_filtops = {
151 .f_isfd = 1,
152 .f_attach = NULL,
153 .f_detach = filt_vndetach,
154 .f_event = filt_vnode,
155 .f_touch = filt_vntouch,
156 .f_process = filt_vnprocess,
157 };
158
159 /*
160 * Common code for vnode open operations.
161 * Check permissions, and call the VNOP_OPEN or VNOP_CREATE routine.
162 *
163 * XXX the profusion of interfaces here is probably a bad thing.
164 */
165 int
166 vn_open(struct nameidata *ndp, int fmode, int cmode)
167 {
168 return(vn_open_modflags(ndp, &fmode, cmode));
169 }
170
171 int
172 vn_open_modflags(struct nameidata *ndp, int *fmodep, int cmode)
173 {
174 struct vnode_attr va;
175
176 VATTR_INIT(&va);
177 VATTR_SET(&va, va_mode, cmode);
178
179 return(vn_open_auth(ndp, fmodep, &va));
180 }
181
182 static int
183 vn_open_auth_finish(vnode_t vp, int fmode, vfs_context_t ctx)
184 {
185 int error;
186
187 if ((error = vnode_ref_ext(vp, fmode, 0)) != 0) {
188 goto bad;
189 }
190
191 /* Call out to allow 3rd party notification of open.
192 * Ignore result of kauth_authorize_fileop call.
193 */
194 #if CONFIG_MACF
195 mac_vnode_notify_open(ctx, vp, fmode);
196 #endif
197 kauth_authorize_fileop(vfs_context_ucred(ctx), KAUTH_FILEOP_OPEN,
198 (uintptr_t)vp, 0);
199
200 return 0;
201
202 bad:
203 return error;
204
205 }
206
207 /*
208 * May do nameidone() to allow safely adding an FSEvent. Cue off of ni_dvp to
209 * determine whether that has happened.
210 */
211 static int
212 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 {
214 uint32_t status = 0;
215 vnode_t dvp = ndp->ni_dvp;
216 int batched;
217 int error;
218 vnode_t vp;
219
220 batched = vnode_compound_open_available(ndp->ni_dvp);
221 *did_open = FALSE;
222
223 VATTR_SET(vap, va_type, VREG);
224 if (fmode & O_EXCL)
225 vap->va_vaflags |= VA_EXCLUSIVE;
226
227 #if NAMEDRSRCFORK
228 if (ndp->ni_cnd.cn_flags & CN_WANTSRSRCFORK) {
229 if ((error = vn_authorize_create(dvp, &ndp->ni_cnd, vap, ctx, NULL)) != 0)
230 goto out;
231 if ((error = vnode_makenamedstream(dvp, &ndp->ni_vp, XATTR_RESOURCEFORK_NAME, 0, ctx)) != 0)
232 goto out;
233 *did_create = TRUE;
234 } else {
235 #endif
236 if (!batched) {
237 if ((error = vn_authorize_create(dvp, &ndp->ni_cnd, vap, ctx, NULL)) != 0)
238 goto out;
239 }
240
241 error = vn_create(dvp, &ndp->ni_vp, ndp, vap, VN_CREATE_DOOPEN, fmode, &status, ctx);
242 if (error != 0) {
243 if (batched) {
244 *did_create = (status & COMPOUND_OPEN_STATUS_DID_CREATE) ? TRUE : FALSE;
245 } else {
246 *did_create = FALSE;
247 }
248
249 if (error == EKEEPLOOKING) {
250 if (*did_create) {
251 panic("EKEEPLOOKING, but we did a create?");
252 }
253 if (!batched) {
254 panic("EKEEPLOOKING from filesystem that doesn't support compound vnops?");
255 }
256 if ((ndp->ni_flag & NAMEI_CONTLOOKUP) == 0) {
257 panic("EKEEPLOOKING, but continue flag not set?");
258 }
259
260 /*
261 * Do NOT drop the dvp: we need everything to continue the lookup.
262 */
263 return error;
264 }
265 } else {
266 if (batched) {
267 *did_create = (status & COMPOUND_OPEN_STATUS_DID_CREATE) ? 1 : 0;
268 *did_open = TRUE;
269 } else {
270 *did_create = TRUE;
271 }
272 }
273 #if NAMEDRSRCFORK
274 }
275 #endif
276
277 vp = ndp->ni_vp;
278
279 if (*did_create) {
280 int update_flags = 0;
281
282 // Make sure the name & parent pointers are hooked up
283 if (vp->v_name == NULL)
284 update_flags |= VNODE_UPDATE_NAME;
285 if (vp->v_parent == NULLVP)
286 update_flags |= VNODE_UPDATE_PARENT;
287
288 if (update_flags)
289 vnode_update_identity(vp, dvp, ndp->ni_cnd.cn_nameptr, ndp->ni_cnd.cn_namelen, ndp->ni_cnd.cn_hash, update_flags);
290
291 vnode_put(dvp);
292 ndp->ni_dvp = NULLVP;
293
294 #if CONFIG_FSE
295 if (need_fsevent(FSE_CREATE_FILE, vp)) {
296 add_fsevent(FSE_CREATE_FILE, ctx,
297 FSE_ARG_VNODE, vp,
298 FSE_ARG_DONE);
299 }
300 #endif
301 }
302 out:
303 if (ndp->ni_dvp != NULLVP) {
304 vnode_put(dvp);
305 ndp->ni_dvp = NULLVP;
306 }
307
308 return error;
309 }
310
311 /*
312 * This is the number of times we'll loop in vn_open_auth without explicitly
313 * yielding the CPU when we determine we have to retry.
314 */
315 #define RETRY_NO_YIELD_COUNT 5
316
317 /*
318 * Open a file with authorization, updating the contents of the structures
319 * pointed to by ndp, fmodep, and vap as necessary to perform the requested
320 * operation. This function is used for both opens of existing files, and
321 * creation of new files.
322 *
323 * Parameters: ndp The nami data pointer describing the
324 * file
325 * fmodep A pointer to an int containg the mode
326 * information to be used for the open
327 * vap A pointer to the vnode attribute
328 * descriptor to be used for the open
329 *
330 * Indirect: * Contents of the data structures pointed
331 * to by the parameters are modified as
332 * necessary to the requested operation.
333 *
334 * Returns: 0 Success
335 * !0 errno value
336 *
337 * Notes: The kauth_filesec_t in 'vap', if any, is in host byte order.
338 *
339 * The contents of '*ndp' will be modified, based on the other
340 * arguments to this function, and to return file and directory
341 * data necessary to satisfy the requested operation.
342 *
343 * If the file does not exist and we are creating it, then the
344 * O_TRUNC flag will be cleared in '*fmodep' to indicate to the
345 * caller that the file was not truncated.
346 *
347 * If the file exists and the O_EXCL flag was not specified, then
348 * the O_CREAT flag will be cleared in '*fmodep' to indicate to
349 * the caller that the existing file was merely opened rather
350 * than created.
351 *
352 * The contents of '*vap' will be modified as necessary to
353 * complete the operation, including setting of supported
354 * attribute, clearing of fields containing unsupported attributes
355 * in the request, if the request proceeds without them, etc..
356 *
357 * XXX: This function is too complicated in actings on its arguments
358 *
359 * XXX: We should enummerate the possible errno values here, and where
360 * in the code they originated.
361 */
362 int
363 vn_open_auth(struct nameidata *ndp, int *fmodep, struct vnode_attr *vap)
364 {
365 struct vnode *vp;
366 struct vnode *dvp;
367 vfs_context_t ctx = ndp->ni_cnd.cn_context;
368 int error;
369 int fmode;
370 uint32_t origcnflags;
371 boolean_t did_create;
372 boolean_t did_open;
373 boolean_t need_vnop_open;
374 boolean_t batched;
375 boolean_t ref_failed;
376 int nretries = 0;
377
378 again:
379 vp = NULL;
380 dvp = NULL;
381 batched = FALSE;
382 did_create = FALSE;
383 need_vnop_open = TRUE;
384 ref_failed = FALSE;
385 fmode = *fmodep;
386 origcnflags = ndp->ni_cnd.cn_flags;
387
388 // If raw encrypted mode is requested, handle that here
389 if (VATTR_IS_ACTIVE (vap, va_dataprotect_flags)
390 && ISSET(vap->va_dataprotect_flags, VA_DP_RAWENCRYPTED)) {
391 fmode |= FENCRYPTED;
392 }
393
394 /*
395 * O_CREAT
396 */
397 if (fmode & O_CREAT) {
398 if ( (fmode & O_DIRECTORY) ) {
399 error = EINVAL;
400 goto out;
401 }
402 ndp->ni_cnd.cn_nameiop = CREATE;
403 #if CONFIG_TRIGGERS
404 ndp->ni_op = OP_LINK;
405 #endif
406 /* Inherit USEDVP, vnode_open() supported flags only */
407 ndp->ni_cnd.cn_flags &= (USEDVP | NOCROSSMOUNT);
408 ndp->ni_cnd.cn_flags |= LOCKPARENT | LOCKLEAF | AUDITVNPATH1;
409 ndp->ni_flag = NAMEI_COMPOUNDOPEN;
410 #if NAMEDRSRCFORK
411 /* open calls are allowed for resource forks. */
412 ndp->ni_cnd.cn_flags |= CN_ALLOWRSRCFORK;
413 #endif
414 if ((fmode & O_EXCL) == 0 && (fmode & O_NOFOLLOW) == 0 && (origcnflags & FOLLOW) != 0)
415 ndp->ni_cnd.cn_flags |= FOLLOW;
416
417 continue_create_lookup:
418 if ( (error = namei(ndp)) )
419 goto out;
420
421 dvp = ndp->ni_dvp;
422 vp = ndp->ni_vp;
423
424 batched = vnode_compound_open_available(dvp);
425
426 /* not found, create */
427 if (vp == NULL) {
428 /* must have attributes for a new file */
429 if (vap == NULL) {
430 vnode_put(dvp);
431 error = EINVAL;
432 goto out;
433 }
434 /*
435 * Attempt a create. For a system supporting compound VNOPs, we may
436 * find an existing file or create one; in either case, we will already
437 * have the file open and no VNOP_OPEN() will be needed.
438 */
439 error = vn_open_auth_do_create(ndp, vap, fmode, &did_create, &did_open, ctx);
440
441 dvp = ndp->ni_dvp;
442 vp = ndp->ni_vp;
443
444 /*
445 * Detected a node that the filesystem couldn't handle. Don't call
446 * nameidone() yet, because we need that path buffer.
447 */
448 if (error == EKEEPLOOKING) {
449 if (!batched) {
450 panic("EKEEPLOOKING from a filesystem that doesn't support compound VNOPs?");
451 }
452 goto continue_create_lookup;
453 }
454
455 nameidone(ndp);
456 if (dvp) {
457 panic("Shouldn't have a dvp here.");
458 }
459
460 if (error) {
461 /*
462 * Check for a create race.
463 */
464 if ((error == EEXIST) && !(fmode & O_EXCL)){
465 if (vp)
466 vnode_put(vp);
467 goto again;
468 }
469 goto bad;
470 }
471
472 need_vnop_open = !did_open;
473 }
474 else {
475 if (fmode & O_EXCL)
476 error = EEXIST;
477
478 /*
479 * We have a vnode. Use compound open if available
480 * or else fall through to "traditional" path. Note: can't
481 * do a compound open for root, because the parent belongs
482 * to a different FS.
483 */
484 if (error == 0 && batched && (vnode_mount(dvp) == vnode_mount(vp))) {
485 error = VNOP_COMPOUND_OPEN(dvp, &ndp->ni_vp, ndp, 0, fmode, NULL, NULL, ctx);
486
487 if (error == 0) {
488 vp = ndp->ni_vp;
489 need_vnop_open = FALSE;
490 } else if (error == EKEEPLOOKING) {
491 if ((ndp->ni_flag & NAMEI_CONTLOOKUP) == 0) {
492 panic("EKEEPLOOKING, but continue flag not set?");
493 }
494 goto continue_create_lookup;
495 }
496 }
497 nameidone(ndp);
498 vnode_put(dvp);
499 ndp->ni_dvp = NULLVP;
500
501 if (error) {
502 goto bad;
503 }
504
505 fmode &= ~O_CREAT;
506
507 /* Fall through */
508 }
509 }
510 else {
511 /*
512 * Not O_CREAT
513 */
514 ndp->ni_cnd.cn_nameiop = LOOKUP;
515 /* Inherit USEDVP, vnode_open() supported flags only */
516 ndp->ni_cnd.cn_flags &= (USEDVP | NOCROSSMOUNT);
517 ndp->ni_cnd.cn_flags |= FOLLOW | LOCKLEAF | AUDITVNPATH1 | WANTPARENT;
518 #if NAMEDRSRCFORK
519 /* open calls are allowed for resource forks. */
520 ndp->ni_cnd.cn_flags |= CN_ALLOWRSRCFORK;
521 #endif
522 if (fmode & FENCRYPTED)
523 ndp->ni_cnd.cn_flags |= CN_RAW_ENCRYPTED | CN_SKIPNAMECACHE;
524 ndp->ni_flag = NAMEI_COMPOUNDOPEN;
525
526 /* preserve NOFOLLOW from vnode_open() */
527 if (fmode & O_NOFOLLOW || fmode & O_SYMLINK || (origcnflags & FOLLOW) == 0) {
528 ndp->ni_cnd.cn_flags &= ~FOLLOW;
529 }
530
531 /* Do a lookup, possibly going directly to filesystem for compound operation */
532 do {
533 if ( (error = namei(ndp)) )
534 goto out;
535 vp = ndp->ni_vp;
536 dvp = ndp->ni_dvp;
537
538 /* Check for batched lookup-open */
539 batched = vnode_compound_open_available(dvp);
540 if (batched && ((vp == NULLVP) || (vnode_mount(dvp) == vnode_mount(vp)))) {
541 error = VNOP_COMPOUND_OPEN(dvp, &ndp->ni_vp, ndp, 0, fmode, NULL, NULL, ctx);
542 vp = ndp->ni_vp;
543 if (error == 0) {
544 need_vnop_open = FALSE;
545 } else if (error == EKEEPLOOKING) {
546 if ((ndp->ni_flag & NAMEI_CONTLOOKUP) == 0) {
547 panic("EKEEPLOOKING, but continue flag not set?");
548 }
549 }
550 }
551 } while (error == EKEEPLOOKING);
552
553 nameidone(ndp);
554 vnode_put(dvp);
555 ndp->ni_dvp = NULLVP;
556
557 if (error) {
558 goto bad;
559 }
560 }
561
562 /*
563 * By this point, nameidone() is called, dvp iocount is dropped,
564 * and dvp pointer is cleared.
565 */
566 if (ndp->ni_dvp != NULLVP) {
567 panic("Haven't cleaned up adequately in vn_open_auth()");
568 }
569
570 /*
571 * Expect to use this code for filesystems without compound VNOPs, for the root
572 * of a filesystem, which can't be "looked up" in the sense of VNOP_LOOKUP(),
573 * and for shadow files, which do not live on the same filesystems as their "parents."
574 */
575 if (need_vnop_open) {
576 if (batched && !vnode_isvroot(vp) && !vnode_isnamedstream(vp)) {
577 panic("Why am I trying to use VNOP_OPEN() on anything other than the root or a named stream?");
578 }
579
580 if (!did_create) {
581 error = vn_authorize_open_existing(vp, &ndp->ni_cnd, fmode, ctx, NULL);
582 if (error) {
583 goto bad;
584 }
585 }
586
587 if (VATTR_IS_ACTIVE (vap, va_dataprotect_flags)
588 && ISSET(vap->va_dataprotect_flags, VA_DP_RAWUNENCRYPTED)) {
589 /* Don't allow unencrypted io request from user space unless entitled */
590 boolean_t entitled = FALSE;
591 #if !SECURE_KERNEL
592 entitled = IOTaskHasEntitlement(current_task(), "com.apple.private.security.file-unencrypt-access");
593 #endif
594 if (!entitled) {
595 error = EPERM;
596 goto bad;
597 }
598 fmode |= FUNENCRYPTED;
599 }
600
601 error = VNOP_OPEN(vp, fmode, ctx);
602 if (error) {
603 goto bad;
604 }
605 need_vnop_open = FALSE;
606 }
607
608 // if the vnode is tagged VOPENEVT and the current process
609 // has the P_CHECKOPENEVT flag set, then we or in the O_EVTONLY
610 // flag to the open mode so that this open won't count against
611 // the vnode when carbon delete() does a vnode_isinuse() to see
612 // if a file is currently in use. this allows spotlight
613 // importers to not interfere with carbon apps that depend on
614 // the no-delete-if-busy semantics of carbon delete().
615 //
616 if (!did_create && (vp->v_flag & VOPENEVT) && (current_proc()->p_flag & P_CHECKOPENEVT)) {
617 fmode |= O_EVTONLY;
618 }
619
620 /*
621 * Grab reference, etc.
622 */
623 error = vn_open_auth_finish(vp, fmode, ctx);
624 if (error) {
625 ref_failed = TRUE;
626 goto bad;
627 }
628
629 /* Compound VNOP open is responsible for doing the truncate */
630 if (batched || did_create)
631 fmode &= ~O_TRUNC;
632
633 *fmodep = fmode;
634 return (0);
635
636 bad:
637 /* Opened either explicitly or by a batched create */
638 if (!need_vnop_open) {
639 VNOP_CLOSE(vp, fmode, ctx);
640 }
641
642 ndp->ni_vp = NULL;
643 if (vp) {
644 #if NAMEDRSRCFORK
645 /* Aggressively recycle shadow files if we error'd out during open() */
646 if ((vnode_isnamedstream(vp)) &&
647 (vp->v_parent != NULLVP) &&
648 (vnode_isshadow(vp))) {
649 vnode_recycle(vp);
650 }
651 #endif
652 vnode_put(vp);
653 /*
654 * Check for a race against unlink. We had a vnode
655 * but according to vnode_authorize or VNOP_OPEN it
656 * no longer exists.
657 *
658 * EREDRIVEOPEN: means that we were hit by the tty allocation race.
659 */
660 if (((error == ENOENT) && (*fmodep & O_CREAT)) || (error == EREDRIVEOPEN) || ref_failed) {
661 /*
662 * We'll retry here but it may be possible that we get
663 * into a retry "spin" inside the kernel and not allow
664 * threads, which need to run in order for the retry
665 * loop to end, to run. An example is an open of a
666 * terminal which is getting revoked and we spin here
667 * without yielding becasue namei and VNOP_OPEN are
668 * successful but vnode_ref fails. The revoke needs
669 * threads with an iocount to run but if spin here we
670 * may possibly be blcoking other threads from running.
671 *
672 * We start yielding the CPU after some number of
673 * retries for increasing durations. Note that this is
674 * still a loop without an exit condition.
675 */
676 nretries += 1;
677 if (nretries > RETRY_NO_YIELD_COUNT) {
678 /* Every hz/100 secs is 10 msecs ... */
679 tsleep(&nretries, PVFS, "vn_open_auth_retry",
680 MIN((nretries * (hz/100)), hz));
681 }
682 goto again;
683 }
684 }
685
686 out:
687 return (error);
688 }
689
690 #if vn_access_DEPRECATED
691 /*
692 * Authorize an action against a vnode. This has been the canonical way to
693 * ensure that the credential/process/etc. referenced by a vfs_context
694 * is granted the rights called out in 'mode' against the vnode 'vp'.
695 *
696 * Unfortunately, the use of VREAD/VWRITE/VEXEC makes it very difficult
697 * to add support for more rights. As such, this interface will be deprecated
698 * and callers will use vnode_authorize instead.
699 */
700 int
701 vn_access(vnode_t vp, int mode, vfs_context_t context)
702 {
703 kauth_action_t action;
704
705 action = 0;
706 if (mode & VREAD)
707 action |= KAUTH_VNODE_READ_DATA;
708 if (mode & VWRITE)
709 action |= KAUTH_VNODE_WRITE_DATA;
710 if (mode & VEXEC)
711 action |= KAUTH_VNODE_EXECUTE;
712
713 return(vnode_authorize(vp, NULL, action, context));
714 }
715 #endif /* vn_access_DEPRECATED */
716
717 /*
718 * Vnode close call
719 */
720 int
721 vn_close(struct vnode *vp, int flags, vfs_context_t ctx)
722 {
723 int error;
724 int flusherror = 0;
725
726 #if NAMEDRSRCFORK
727 /* Sync data from resource fork shadow file if needed. */
728 if ((vp->v_flag & VISNAMEDSTREAM) &&
729 (vp->v_parent != NULLVP) &&
730 vnode_isshadow(vp)) {
731 if (flags & FWASWRITTEN) {
732 flusherror = vnode_flushnamedstream(vp->v_parent, vp, ctx);
733 }
734 }
735 #endif
736
737 /* work around for foxhound */
738 if (vnode_isspec(vp))
739 (void)vnode_rele_ext(vp, flags, 0);
740
741 /*
742 * On HFS, we flush when the last writer closes. We do this
743 * because resource fork vnodes hold a reference on data fork
744 * vnodes and that will prevent them from getting VNOP_INACTIVE
745 * which will delay when we flush cached data. In future, we
746 * might find it beneficial to do this for all file systems.
747 * Note that it's OK to access v_writecount without the lock
748 * in this context.
749 */
750 if (vp->v_tag == VT_HFS && (flags & FWRITE) && vp->v_writecount == 1)
751 VNOP_FSYNC(vp, MNT_NOWAIT, ctx);
752
753 error = VNOP_CLOSE(vp, flags, ctx);
754
755 #if CONFIG_FSE
756 if (flags & FWASWRITTEN) {
757 if (need_fsevent(FSE_CONTENT_MODIFIED, vp)) {
758 add_fsevent(FSE_CONTENT_MODIFIED, ctx,
759 FSE_ARG_VNODE, vp,
760 FSE_ARG_DONE);
761 }
762 }
763 #endif
764
765 if (!vnode_isspec(vp))
766 (void)vnode_rele_ext(vp, flags, 0);
767
768 if (flusherror) {
769 error = flusherror;
770 }
771 return (error);
772 }
773
774 static int
775 vn_read_swapfile(
776 struct vnode *vp,
777 uio_t uio)
778 {
779 int error;
780 off_t swap_count, this_count;
781 off_t file_end, read_end;
782 off_t prev_resid;
783 char *my_swap_page;
784
785 /*
786 * Reading from a swap file will get you zeroes.
787 */
788
789 my_swap_page = NULL;
790 error = 0;
791 swap_count = uio_resid(uio);
792
793 file_end = ubc_getsize(vp);
794 read_end = uio->uio_offset + uio_resid(uio);
795 if (uio->uio_offset >= file_end) {
796 /* uio starts after end of file: nothing to read */
797 swap_count = 0;
798 } else if (read_end > file_end) {
799 /* uio extends beyond end of file: stop before that */
800 swap_count -= (read_end - file_end);
801 }
802
803 while (swap_count > 0) {
804 if (my_swap_page == NULL) {
805 MALLOC(my_swap_page, char *, PAGE_SIZE,
806 M_TEMP, M_WAITOK);
807 memset(my_swap_page, '\0', PAGE_SIZE);
808 /* add an end-of-line to keep line counters happy */
809 my_swap_page[PAGE_SIZE-1] = '\n';
810 }
811 this_count = swap_count;
812 if (this_count > PAGE_SIZE) {
813 this_count = PAGE_SIZE;
814 }
815
816 prev_resid = uio_resid(uio);
817 error = uiomove((caddr_t) my_swap_page,
818 this_count,
819 uio);
820 if (error) {
821 break;
822 }
823 swap_count -= (prev_resid - uio_resid(uio));
824 }
825 if (my_swap_page != NULL) {
826 FREE(my_swap_page, M_TEMP);
827 my_swap_page = NULL;
828 }
829
830 return error;
831 }
832 /*
833 * Package up an I/O request on a vnode into a uio and do it.
834 */
835 int
836 vn_rdwr(
837 enum uio_rw rw,
838 struct vnode *vp,
839 caddr_t base,
840 int len,
841 off_t offset,
842 enum uio_seg segflg,
843 int ioflg,
844 kauth_cred_t cred,
845 int *aresid,
846 proc_t p)
847 {
848 int64_t resid;
849 int result;
850
851 result = vn_rdwr_64(rw,
852 vp,
853 (uint64_t)(uintptr_t)base,
854 (int64_t)len,
855 offset,
856 segflg,
857 ioflg,
858 cred,
859 &resid,
860 p);
861
862 /* "resid" should be bounded above by "len," which is an int */
863 if (aresid != NULL) {
864 *aresid = resid;
865 }
866
867 return result;
868 }
869
870
871 int
872 vn_rdwr_64(
873 enum uio_rw rw,
874 struct vnode *vp,
875 uint64_t base,
876 int64_t len,
877 off_t offset,
878 enum uio_seg segflg,
879 int ioflg,
880 kauth_cred_t cred,
881 int64_t *aresid,
882 proc_t p)
883 {
884 uio_t auio;
885 int spacetype;
886 struct vfs_context context;
887 int error=0;
888 char uio_buf[ UIO_SIZEOF(1) ];
889
890 context.vc_thread = current_thread();
891 context.vc_ucred = cred;
892
893 if (UIO_SEG_IS_USER_SPACE(segflg)) {
894 spacetype = proc_is64bit(p) ? UIO_USERSPACE64 : UIO_USERSPACE32;
895 }
896 else {
897 spacetype = UIO_SYSSPACE;
898 }
899 auio = uio_createwithbuffer(1, offset, spacetype, rw,
900 &uio_buf[0], sizeof(uio_buf));
901 uio_addiov(auio, base, len);
902
903 #if CONFIG_MACF
904 /* XXXMAC
905 * IO_NOAUTH should be re-examined.
906 * Likely that mediation should be performed in caller.
907 */
908 if ((ioflg & IO_NOAUTH) == 0) {
909 /* passed cred is fp->f_cred */
910 if (rw == UIO_READ)
911 error = mac_vnode_check_read(&context, cred, vp);
912 else
913 error = mac_vnode_check_write(&context, cred, vp);
914 }
915 #endif
916
917 if (error == 0) {
918 if (rw == UIO_READ) {
919 if (vnode_isswap(vp) && ((ioflg & IO_SWAP_DISPATCH) == 0)) {
920 error = vn_read_swapfile(vp, auio);
921 } else {
922 error = VNOP_READ(vp, auio, ioflg, &context);
923 }
924 } else {
925 error = VNOP_WRITE(vp, auio, ioflg, &context);
926 }
927 }
928
929 if (aresid)
930 *aresid = uio_resid(auio);
931 else
932 if (uio_resid(auio) && error == 0)
933 error = EIO;
934 return (error);
935 }
936
937 static inline void
938 vn_offset_lock(struct fileglob *fg)
939 {
940 lck_mtx_lock_spin(&fg->fg_lock);
941 while (fg->fg_lflags & FG_OFF_LOCKED) {
942 fg->fg_lflags |= FG_OFF_LOCKWANT;
943 msleep(&fg->fg_lflags, &fg->fg_lock, PVFS | PSPIN,
944 "fg_offset_lock_wait", 0);
945 }
946 fg->fg_lflags |= FG_OFF_LOCKED;
947 lck_mtx_unlock(&fg->fg_lock);
948 }
949
950 static inline void
951 vn_offset_unlock(struct fileglob *fg)
952 {
953 int lock_wanted = 0;
954
955 lck_mtx_lock_spin(&fg->fg_lock);
956 if (fg->fg_lflags & FG_OFF_LOCKWANT) {
957 lock_wanted = 1;
958 }
959 fg->fg_lflags &= ~(FG_OFF_LOCKED | FG_OFF_LOCKWANT);
960 lck_mtx_unlock(&fg->fg_lock);
961 if (lock_wanted) {
962 wakeup(&fg->fg_lflags);
963 }
964 }
965
966 /*
967 * File table vnode read routine.
968 */
969 static int
970 vn_read(struct fileproc *fp, struct uio *uio, int flags, vfs_context_t ctx)
971 {
972 struct vnode *vp;
973 int error;
974 int ioflag;
975 off_t count;
976 int offset_locked = 0;
977
978 vp = (struct vnode *)fp->f_fglob->fg_data;
979 if ( (error = vnode_getwithref(vp)) ) {
980 return(error);
981 }
982
983 #if CONFIG_MACF
984 error = mac_vnode_check_read(ctx, vfs_context_ucred(ctx), vp);
985 if (error) {
986 (void)vnode_put(vp);
987 return (error);
988 }
989 #endif
990
991 /* This signals to VNOP handlers that this read came from a file table read */
992 ioflag = IO_SYSCALL_DISPATCH;
993
994 if (fp->f_fglob->fg_flag & FNONBLOCK)
995 ioflag |= IO_NDELAY;
996 if ((fp->f_fglob->fg_flag & FNOCACHE) || vnode_isnocache(vp))
997 ioflag |= IO_NOCACHE;
998 if (fp->f_fglob->fg_flag & FENCRYPTED) {
999 ioflag |= IO_ENCRYPTED;
1000 }
1001 if (fp->f_fglob->fg_flag & FUNENCRYPTED) {
1002 ioflag |= IO_SKIP_ENCRYPTION;
1003 }
1004 if (fp->f_fglob->fg_flag & O_EVTONLY) {
1005 ioflag |= IO_EVTONLY;
1006 }
1007 if (fp->f_fglob->fg_flag & FNORDAHEAD)
1008 ioflag |= IO_RAOFF;
1009
1010 if ((flags & FOF_OFFSET) == 0) {
1011 if ((vnode_vtype(vp) == VREG) && !vnode_isswap(vp)) {
1012 vn_offset_lock(fp->f_fglob);
1013 offset_locked = 1;
1014 }
1015 uio->uio_offset = fp->f_fglob->fg_offset;
1016 }
1017 count = uio_resid(uio);
1018
1019 if (vnode_isswap(vp) && !(IO_SKIP_ENCRYPTION & ioflag)) {
1020 /* special case for swap files */
1021 error = vn_read_swapfile(vp, uio);
1022 } else {
1023 error = VNOP_READ(vp, uio, ioflag, ctx);
1024 }
1025 if ((flags & FOF_OFFSET) == 0) {
1026 fp->f_fglob->fg_offset += count - uio_resid(uio);
1027 if (offset_locked) {
1028 vn_offset_unlock(fp->f_fglob);
1029 offset_locked = 0;
1030 }
1031 }
1032
1033 (void)vnode_put(vp);
1034 return (error);
1035 }
1036
1037
1038 /*
1039 * File table vnode write routine.
1040 */
1041 static int
1042 vn_write(struct fileproc *fp, struct uio *uio, int flags, vfs_context_t ctx)
1043 {
1044 struct vnode *vp;
1045 int error, ioflag;
1046 off_t count;
1047 int clippedsize = 0;
1048 int partialwrite=0;
1049 int residcount, oldcount;
1050 int offset_locked = 0;
1051 proc_t p = vfs_context_proc(ctx);
1052
1053 count = 0;
1054 vp = (struct vnode *)fp->f_fglob->fg_data;
1055 if ( (error = vnode_getwithref(vp)) ) {
1056 return(error);
1057 }
1058
1059 #if CONFIG_MACF
1060 error = mac_vnode_check_write(ctx, vfs_context_ucred(ctx), vp);
1061 if (error) {
1062 (void)vnode_put(vp);
1063 return (error);
1064 }
1065 #endif
1066
1067 /*
1068 * IO_SYSCALL_DISPATCH signals to VNOP handlers that this write came from
1069 * a file table write
1070 */
1071 ioflag = (IO_UNIT | IO_SYSCALL_DISPATCH);
1072
1073 if (vp->v_type == VREG && (fp->f_fglob->fg_flag & O_APPEND))
1074 ioflag |= IO_APPEND;
1075 if (fp->f_fglob->fg_flag & FNONBLOCK)
1076 ioflag |= IO_NDELAY;
1077 if ((fp->f_fglob->fg_flag & FNOCACHE) || vnode_isnocache(vp))
1078 ioflag |= IO_NOCACHE;
1079 if (fp->f_fglob->fg_flag & FNODIRECT)
1080 ioflag |= IO_NODIRECT;
1081 if (fp->f_fglob->fg_flag & FSINGLE_WRITER)
1082 ioflag |= IO_SINGLE_WRITER;
1083 if (fp->f_fglob->fg_flag & O_EVTONLY)
1084 ioflag |= IO_EVTONLY;
1085
1086 /*
1087 * Treat synchronous mounts and O_FSYNC on the fd as equivalent.
1088 *
1089 * XXX We treat O_DSYNC as O_FSYNC for now, since we can not delay
1090 * XXX the non-essential metadata without some additional VFS work;
1091 * XXX the intent at this point is to plumb the interface for it.
1092 */
1093 if ((fp->f_fglob->fg_flag & (O_FSYNC|O_DSYNC)) ||
1094 (vp->v_mount && (vp->v_mount->mnt_flag & MNT_SYNCHRONOUS))) {
1095 ioflag |= IO_SYNC;
1096 }
1097
1098 if ((flags & FOF_OFFSET) == 0) {
1099 if ((vnode_vtype(vp) == VREG) && !vnode_isswap(vp)) {
1100 vn_offset_lock(fp->f_fglob);
1101 offset_locked = 1;
1102 }
1103 uio->uio_offset = fp->f_fglob->fg_offset;
1104 count = uio_resid(uio);
1105 }
1106 if (((flags & FOF_OFFSET) == 0) &&
1107 vfs_context_proc(ctx) && (vp->v_type == VREG) &&
1108 (((rlim_t)(uio->uio_offset + uio_resid(uio)) > p->p_rlimit[RLIMIT_FSIZE].rlim_cur) ||
1109 ((rlim_t)uio_resid(uio) > (p->p_rlimit[RLIMIT_FSIZE].rlim_cur - uio->uio_offset)))) {
1110 /*
1111 * If the requested residual would cause us to go past the
1112 * administrative limit, then we need to adjust the residual
1113 * down to cause fewer bytes than requested to be written. If
1114 * we can't do that (e.g. the residual is already 1 byte),
1115 * then we fail the write with EFBIG.
1116 */
1117 residcount = uio_resid(uio);
1118 if ((rlim_t)(uio->uio_offset + uio_resid(uio)) > p->p_rlimit[RLIMIT_FSIZE].rlim_cur) {
1119 clippedsize = (uio->uio_offset + uio_resid(uio)) - p->p_rlimit[RLIMIT_FSIZE].rlim_cur;
1120 } else if ((rlim_t)uio_resid(uio) > (p->p_rlimit[RLIMIT_FSIZE].rlim_cur - uio->uio_offset)) {
1121 clippedsize = (p->p_rlimit[RLIMIT_FSIZE].rlim_cur - uio->uio_offset);
1122 }
1123 if (clippedsize >= residcount) {
1124 psignal(p, SIGXFSZ);
1125 error = EFBIG;
1126 goto error_out;
1127 }
1128 partialwrite = 1;
1129 uio_setresid(uio, residcount-clippedsize);
1130 }
1131 if ((flags & FOF_OFFSET) != 0) {
1132 /* for pwrite, append should be ignored */
1133 ioflag &= ~IO_APPEND;
1134 if (p && (vp->v_type == VREG) &&
1135 ((rlim_t)uio->uio_offset >= p->p_rlimit[RLIMIT_FSIZE].rlim_cur)) {
1136 psignal(p, SIGXFSZ);
1137 error = EFBIG;
1138 goto error_out;
1139 }
1140 if (p && (vp->v_type == VREG) &&
1141 ((rlim_t)(uio->uio_offset + uio_resid(uio)) > p->p_rlimit[RLIMIT_FSIZE].rlim_cur)) {
1142 //Debugger("vn_bwrite:overstepping the bounds");
1143 residcount = uio_resid(uio);
1144 clippedsize = (uio->uio_offset + uio_resid(uio)) - p->p_rlimit[RLIMIT_FSIZE].rlim_cur;
1145 partialwrite = 1;
1146 uio_setresid(uio, residcount-clippedsize);
1147 }
1148 }
1149
1150 error = VNOP_WRITE(vp, uio, ioflag, ctx);
1151
1152 if (partialwrite) {
1153 oldcount = uio_resid(uio);
1154 uio_setresid(uio, oldcount + clippedsize);
1155 }
1156
1157 if ((flags & FOF_OFFSET) == 0) {
1158 if (ioflag & IO_APPEND)
1159 fp->f_fglob->fg_offset = uio->uio_offset;
1160 else
1161 fp->f_fglob->fg_offset += count - uio_resid(uio);
1162 if (offset_locked) {
1163 vn_offset_unlock(fp->f_fglob);
1164 offset_locked = 0;
1165 }
1166 }
1167
1168 /*
1169 * Set the credentials on successful writes
1170 */
1171 if ((error == 0) && (vp->v_tag == VT_NFS) && (UBCINFOEXISTS(vp))) {
1172 /*
1173 * When called from aio subsystem, we only have the proc from
1174 * which to get the credential, at this point, so use that
1175 * instead. This means aio functions are incompatible with
1176 * per-thread credentials (aio operations are proxied). We
1177 * can't easily correct the aio vs. settid race in this case
1178 * anyway, so we disallow it.
1179 */
1180 if ((flags & FOF_PCRED) == 0) {
1181 ubc_setthreadcred(vp, p, current_thread());
1182 } else {
1183 ubc_setcred(vp, p);
1184 }
1185 }
1186 (void)vnode_put(vp);
1187 return (error);
1188
1189 error_out:
1190 if (offset_locked) {
1191 vn_offset_unlock(fp->f_fglob);
1192 }
1193 (void)vnode_put(vp);
1194 return (error);
1195 }
1196
1197 /*
1198 * File table vnode stat routine.
1199 *
1200 * Returns: 0 Success
1201 * EBADF
1202 * ENOMEM
1203 * vnode_getattr:???
1204 */
1205 int
1206 vn_stat_noauth(struct vnode *vp, void *sbptr, kauth_filesec_t *xsec, int isstat64, vfs_context_t ctx)
1207 {
1208 struct vnode_attr va;
1209 int error;
1210 u_short mode;
1211 kauth_filesec_t fsec;
1212 struct stat *sb = (struct stat *)0; /* warning avoidance ; protected by isstat64 */
1213 struct stat64 * sb64 = (struct stat64 *)0; /* warning avoidance ; protected by isstat64 */
1214
1215 if (isstat64 != 0)
1216 sb64 = (struct stat64 *)sbptr;
1217 else
1218 sb = (struct stat *)sbptr;
1219 memset(&va, 0, sizeof(va));
1220 VATTR_INIT(&va);
1221 VATTR_WANTED(&va, va_fsid);
1222 VATTR_WANTED(&va, va_fileid);
1223 VATTR_WANTED(&va, va_mode);
1224 VATTR_WANTED(&va, va_type);
1225 VATTR_WANTED(&va, va_nlink);
1226 VATTR_WANTED(&va, va_uid);
1227 VATTR_WANTED(&va, va_gid);
1228 VATTR_WANTED(&va, va_rdev);
1229 VATTR_WANTED(&va, va_data_size);
1230 VATTR_WANTED(&va, va_access_time);
1231 VATTR_WANTED(&va, va_modify_time);
1232 VATTR_WANTED(&va, va_change_time);
1233 VATTR_WANTED(&va, va_create_time);
1234 VATTR_WANTED(&va, va_flags);
1235 VATTR_WANTED(&va, va_gen);
1236 VATTR_WANTED(&va, va_iosize);
1237 /* lower layers will synthesise va_total_alloc from va_data_size if required */
1238 VATTR_WANTED(&va, va_total_alloc);
1239 if (xsec != NULL) {
1240 VATTR_WANTED(&va, va_uuuid);
1241 VATTR_WANTED(&va, va_guuid);
1242 VATTR_WANTED(&va, va_acl);
1243 }
1244 error = vnode_getattr(vp, &va, ctx);
1245 if (error)
1246 goto out;
1247 /*
1248 * Copy from vattr table
1249 */
1250 if (isstat64 != 0) {
1251 sb64->st_dev = va.va_fsid;
1252 sb64->st_ino = (ino64_t)va.va_fileid;
1253
1254 } else {
1255 sb->st_dev = va.va_fsid;
1256 sb->st_ino = (ino_t)va.va_fileid;
1257 }
1258 mode = va.va_mode;
1259 switch (vp->v_type) {
1260 case VREG:
1261 mode |= S_IFREG;
1262 break;
1263 case VDIR:
1264 mode |= S_IFDIR;
1265 break;
1266 case VBLK:
1267 mode |= S_IFBLK;
1268 break;
1269 case VCHR:
1270 mode |= S_IFCHR;
1271 break;
1272 case VLNK:
1273 mode |= S_IFLNK;
1274 break;
1275 case VSOCK:
1276 mode |= S_IFSOCK;
1277 break;
1278 case VFIFO:
1279 mode |= S_IFIFO;
1280 break;
1281 default:
1282 error = EBADF;
1283 goto out;
1284 };
1285 if (isstat64 != 0) {
1286 sb64->st_mode = mode;
1287 sb64->st_nlink = VATTR_IS_SUPPORTED(&va, va_nlink) ? (u_int16_t)va.va_nlink : 1;
1288 sb64->st_uid = va.va_uid;
1289 sb64->st_gid = va.va_gid;
1290 sb64->st_rdev = va.va_rdev;
1291 sb64->st_size = va.va_data_size;
1292 sb64->st_atimespec = va.va_access_time;
1293 sb64->st_mtimespec = va.va_modify_time;
1294 sb64->st_ctimespec = va.va_change_time;
1295 if (VATTR_IS_SUPPORTED(&va, va_create_time)) {
1296 sb64->st_birthtimespec = va.va_create_time;
1297 } else {
1298 sb64->st_birthtimespec.tv_sec = sb64->st_birthtimespec.tv_nsec = 0;
1299 }
1300 sb64->st_blksize = va.va_iosize;
1301 sb64->st_flags = va.va_flags;
1302 sb64->st_blocks = roundup(va.va_total_alloc, 512) / 512;
1303 } else {
1304 sb->st_mode = mode;
1305 sb->st_nlink = VATTR_IS_SUPPORTED(&va, va_nlink) ? (u_int16_t)va.va_nlink : 1;
1306 sb->st_uid = va.va_uid;
1307 sb->st_gid = va.va_gid;
1308 sb->st_rdev = va.va_rdev;
1309 sb->st_size = va.va_data_size;
1310 sb->st_atimespec = va.va_access_time;
1311 sb->st_mtimespec = va.va_modify_time;
1312 sb->st_ctimespec = va.va_change_time;
1313 sb->st_blksize = va.va_iosize;
1314 sb->st_flags = va.va_flags;
1315 sb->st_blocks = roundup(va.va_total_alloc, 512) / 512;
1316 }
1317
1318 /* if we're interested in extended security data and we got an ACL */
1319 if (xsec != NULL) {
1320 if (!VATTR_IS_SUPPORTED(&va, va_acl) &&
1321 !VATTR_IS_SUPPORTED(&va, va_uuuid) &&
1322 !VATTR_IS_SUPPORTED(&va, va_guuid)) {
1323 *xsec = KAUTH_FILESEC_NONE;
1324 } else {
1325
1326 if (VATTR_IS_SUPPORTED(&va, va_acl) && (va.va_acl != NULL)) {
1327 fsec = kauth_filesec_alloc(va.va_acl->acl_entrycount);
1328 } else {
1329 fsec = kauth_filesec_alloc(0);
1330 }
1331 if (fsec == NULL) {
1332 error = ENOMEM;
1333 goto out;
1334 }
1335 fsec->fsec_magic = KAUTH_FILESEC_MAGIC;
1336 if (VATTR_IS_SUPPORTED(&va, va_uuuid)) {
1337 fsec->fsec_owner = va.va_uuuid;
1338 } else {
1339 fsec->fsec_owner = kauth_null_guid;
1340 }
1341 if (VATTR_IS_SUPPORTED(&va, va_guuid)) {
1342 fsec->fsec_group = va.va_guuid;
1343 } else {
1344 fsec->fsec_group = kauth_null_guid;
1345 }
1346 if (VATTR_IS_SUPPORTED(&va, va_acl) && (va.va_acl != NULL)) {
1347 bcopy(va.va_acl, &(fsec->fsec_acl), KAUTH_ACL_COPYSIZE(va.va_acl));
1348 } else {
1349 fsec->fsec_acl.acl_entrycount = KAUTH_FILESEC_NOACL;
1350 }
1351 *xsec = fsec;
1352 }
1353 }
1354
1355 /* Do not give the generation number out to unpriviledged users */
1356 if (va.va_gen && !vfs_context_issuser(ctx)) {
1357 if (isstat64 != 0)
1358 sb64->st_gen = 0;
1359 else
1360 sb->st_gen = 0;
1361 } else {
1362 if (isstat64 != 0)
1363 sb64->st_gen = va.va_gen;
1364 else
1365 sb->st_gen = va.va_gen;
1366 }
1367
1368 error = 0;
1369 out:
1370 if (VATTR_IS_SUPPORTED(&va, va_acl) && va.va_acl != NULL)
1371 kauth_acl_free(va.va_acl);
1372 return (error);
1373 }
1374
1375 int
1376 vn_stat(struct vnode *vp, void *sb, kauth_filesec_t *xsec, int isstat64, vfs_context_t ctx)
1377 {
1378 int error;
1379
1380 #if CONFIG_MACF
1381 error = mac_vnode_check_stat(ctx, NOCRED, vp);
1382 if (error)
1383 return (error);
1384 #endif
1385
1386 /* authorize */
1387 if ((error = vnode_authorize(vp, NULL, KAUTH_VNODE_READ_ATTRIBUTES | KAUTH_VNODE_READ_SECURITY, ctx)) != 0)
1388 return(error);
1389
1390 /* actual stat */
1391 return(vn_stat_noauth(vp, sb, xsec, isstat64, ctx));
1392 }
1393
1394
1395 /*
1396 * File table vnode ioctl routine.
1397 */
1398 static int
1399 vn_ioctl(struct fileproc *fp, u_long com, caddr_t data, vfs_context_t ctx)
1400 {
1401 struct vnode *vp = ((struct vnode *)fp->f_fglob->fg_data);
1402 off_t file_size;
1403 int error;
1404 struct vnode *ttyvp;
1405 struct session * sessp;
1406
1407 if ( (error = vnode_getwithref(vp)) ) {
1408 return(error);
1409 }
1410
1411 #if CONFIG_MACF
1412 error = mac_vnode_check_ioctl(ctx, vp, com);
1413 if (error)
1414 goto out;
1415 #endif
1416
1417 switch (vp->v_type) {
1418 case VREG:
1419 case VDIR:
1420 if (com == FIONREAD) {
1421 if ((error = vnode_size(vp, &file_size, ctx)) != 0)
1422 goto out;
1423 *(int *)data = file_size - fp->f_fglob->fg_offset;
1424 goto out;
1425 }
1426 if (com == FIONBIO || com == FIOASYNC) { /* XXX */
1427 goto out;
1428 }
1429 /* fall into ... */
1430
1431 default:
1432 error = ENOTTY;
1433 goto out;
1434
1435 case VFIFO:
1436 case VCHR:
1437 case VBLK:
1438
1439 /* Should not be able to set block size from user space */
1440 if (com == DKIOCSETBLOCKSIZE) {
1441 error = EPERM;
1442 goto out;
1443 }
1444
1445 if (com == FIODTYPE) {
1446 if (vp->v_type == VBLK) {
1447 if (major(vp->v_rdev) >= nblkdev) {
1448 error = ENXIO;
1449 goto out;
1450 }
1451 *(int *)data = bdevsw[major(vp->v_rdev)].d_type;
1452
1453 } else if (vp->v_type == VCHR) {
1454 if (major(vp->v_rdev) >= nchrdev) {
1455 error = ENXIO;
1456 goto out;
1457 }
1458 *(int *)data = cdevsw[major(vp->v_rdev)].d_type;
1459 } else {
1460 error = ENOTTY;
1461 goto out;
1462 }
1463 goto out;
1464 }
1465 error = VNOP_IOCTL(vp, com, data, fp->f_fglob->fg_flag, ctx);
1466
1467 if (error == 0 && com == TIOCSCTTY) {
1468 sessp = proc_session(vfs_context_proc(ctx));
1469
1470 session_lock(sessp);
1471 ttyvp = sessp->s_ttyvp;
1472 sessp->s_ttyvp = vp;
1473 sessp->s_ttyvid = vnode_vid(vp);
1474 session_unlock(sessp);
1475 session_rele(sessp);
1476 }
1477 }
1478 out:
1479 (void)vnode_put(vp);
1480 return(error);
1481 }
1482
1483 /*
1484 * File table vnode select routine.
1485 */
1486 static int
1487 vn_select(struct fileproc *fp, int which, void *wql, __unused vfs_context_t ctx)
1488 {
1489 int error;
1490 struct vnode * vp = (struct vnode *)fp->f_fglob->fg_data;
1491 struct vfs_context context;
1492
1493 if ( (error = vnode_getwithref(vp)) == 0 ) {
1494 context.vc_thread = current_thread();
1495 context.vc_ucred = fp->f_fglob->fg_cred;
1496
1497 #if CONFIG_MACF
1498 /*
1499 * XXX We should use a per thread credential here; minimally,
1500 * XXX the process credential should have a persistent
1501 * XXX reference on it before being passed in here.
1502 */
1503 error = mac_vnode_check_select(ctx, vp, which);
1504 if (error == 0)
1505 #endif
1506 error = VNOP_SELECT(vp, which, fp->f_fglob->fg_flag, wql, ctx);
1507
1508 (void)vnode_put(vp);
1509 }
1510 return(error);
1511
1512 }
1513
1514 /*
1515 * File table vnode close routine.
1516 */
1517 static int
1518 vn_closefile(struct fileglob *fg, vfs_context_t ctx)
1519 {
1520 struct vnode *vp = fg->fg_data;
1521 int error;
1522
1523 if ( (error = vnode_getwithref(vp)) == 0 ) {
1524 if (FILEGLOB_DTYPE(fg) == DTYPE_VNODE &&
1525 ((fg->fg_flag & FHASLOCK) != 0 ||
1526 (fg->fg_lflags & FG_HAS_OFDLOCK) != 0)) {
1527 struct flock lf = {
1528 .l_whence = SEEK_SET,
1529 .l_start = 0,
1530 .l_len = 0,
1531 .l_type = F_UNLCK
1532 };
1533
1534 if ((fg->fg_flag & FHASLOCK) != 0)
1535 (void) VNOP_ADVLOCK(vp, (caddr_t)fg,
1536 F_UNLCK, &lf, F_FLOCK, ctx, NULL);
1537
1538 if ((fg->fg_lflags & FG_HAS_OFDLOCK) != 0)
1539 (void) VNOP_ADVLOCK(vp, (caddr_t)fg,
1540 F_UNLCK, &lf, F_OFD_LOCK, ctx, NULL);
1541 }
1542 error = vn_close(vp, fg->fg_flag, ctx);
1543 (void) vnode_put(vp);
1544 }
1545 return (error);
1546 }
1547
1548 /*
1549 * Returns: 0 Success
1550 * VNOP_PATHCONF:???
1551 */
1552 int
1553 vn_pathconf(vnode_t vp, int name, int32_t *retval, vfs_context_t ctx)
1554 {
1555 int error = 0;
1556 struct vfs_attr vfa;
1557
1558 switch(name) {
1559 case _PC_EXTENDED_SECURITY_NP:
1560 *retval = vfs_extendedsecurity(vnode_mount(vp)) ? 1 : 0;
1561 break;
1562 case _PC_AUTH_OPAQUE_NP:
1563 *retval = vfs_authopaque(vnode_mount(vp));
1564 break;
1565 case _PC_2_SYMLINKS:
1566 *retval = 1; /* XXX NOTSUP on MSDOS, etc. */
1567 break;
1568 case _PC_ALLOC_SIZE_MIN:
1569 *retval = 1; /* XXX lie: 1 byte */
1570 break;
1571 case _PC_ASYNC_IO: /* unistd.h: _POSIX_ASYNCHRONUS_IO */
1572 *retval = 1; /* [AIO] option is supported */
1573 break;
1574 case _PC_PRIO_IO: /* unistd.h: _POSIX_PRIORITIZED_IO */
1575 *retval = 0; /* [PIO] option is not supported */
1576 break;
1577 case _PC_REC_INCR_XFER_SIZE:
1578 *retval = 4096; /* XXX go from MIN to MAX 4K at a time */
1579 break;
1580 case _PC_REC_MIN_XFER_SIZE:
1581 *retval = 4096; /* XXX recommend 4K minimum reads/writes */
1582 break;
1583 case _PC_REC_MAX_XFER_SIZE:
1584 *retval = 65536; /* XXX recommend 64K maximum reads/writes */
1585 break;
1586 case _PC_REC_XFER_ALIGN:
1587 *retval = 4096; /* XXX recommend page aligned buffers */
1588 break;
1589 case _PC_SYMLINK_MAX:
1590 *retval = 255; /* Minimum acceptable POSIX value */
1591 break;
1592 case _PC_SYNC_IO: /* unistd.h: _POSIX_SYNCHRONIZED_IO */
1593 *retval = 0; /* [SIO] option is not supported */
1594 break;
1595 case _PC_XATTR_SIZE_BITS:
1596 /* The number of bits used to store maximum extended
1597 * attribute size in bytes. For example, if the maximum
1598 * attribute size supported by a file system is 128K, the
1599 * value returned will be 18. However a value 18 can mean
1600 * that the maximum attribute size can be anywhere from
1601 * (256KB - 1) to 128KB. As a special case, the resource
1602 * fork can have much larger size, and some file system
1603 * specific extended attributes can have smaller and preset
1604 * size; for example, Finder Info is always 32 bytes.
1605 */
1606 memset(&vfa, 0, sizeof(vfa));
1607 VFSATTR_INIT(&vfa);
1608 VFSATTR_WANTED(&vfa, f_capabilities);
1609 if (vfs_getattr(vnode_mount(vp), &vfa, ctx) == 0 &&
1610 (VFSATTR_IS_SUPPORTED(&vfa, f_capabilities)) &&
1611 (vfa.f_capabilities.capabilities[VOL_CAPABILITIES_INTERFACES] & VOL_CAP_INT_EXTENDED_ATTR) &&
1612 (vfa.f_capabilities.valid[VOL_CAPABILITIES_INTERFACES] & VOL_CAP_INT_EXTENDED_ATTR)) {
1613 /* Supports native extended attributes */
1614 error = VNOP_PATHCONF(vp, name, retval, ctx);
1615 } else {
1616 /* Number of bits used to represent the maximum size of
1617 * extended attribute stored in an Apple Double file.
1618 */
1619 *retval = AD_XATTR_SIZE_BITS;
1620 }
1621 break;
1622 default:
1623 error = VNOP_PATHCONF(vp, name, retval, ctx);
1624 break;
1625 }
1626
1627 return (error);
1628 }
1629
1630 static int
1631 vn_kqfilt_add(struct fileproc *fp, struct knote *kn, vfs_context_t ctx)
1632 {
1633 struct vnode *vp;
1634 int error = 0;
1635 int result = 0;
1636
1637 vp = (struct vnode *)fp->f_fglob->fg_data;
1638
1639 /*
1640 * Don't attach a knote to a dead vnode.
1641 */
1642 if ((error = vget_internal(vp, 0, VNODE_NODEAD)) == 0) {
1643 switch (kn->kn_filter) {
1644 case EVFILT_READ:
1645 case EVFILT_WRITE:
1646 if (vnode_isfifo(vp)) {
1647 /* We'll only watch FIFOs that use our fifofs */
1648 if (!(vp->v_fifoinfo && vp->v_fifoinfo->fi_readsock)) {
1649 error = ENOTSUP;
1650 }
1651
1652 } else if (!vnode_isreg(vp)) {
1653 if (vnode_ischr(vp)) {
1654 result = spec_kqfilter(vp, kn);
1655 if ((kn->kn_flags & EV_ERROR) == 0) {
1656 /* claimed by a special device */
1657 vnode_put(vp);
1658 return result;
1659 }
1660 }
1661 error = EINVAL;
1662 }
1663 break;
1664 case EVFILT_VNODE:
1665 break;
1666 default:
1667 error = EINVAL;
1668 }
1669
1670 if (error == 0) {
1671
1672 #if CONFIG_MACF
1673 error = mac_vnode_check_kqfilter(ctx, fp->f_fglob->fg_cred, kn, vp);
1674 if (error) {
1675 vnode_put(vp);
1676 goto out;
1677 }
1678 #endif
1679
1680 kn->kn_hook = (void*)vp;
1681 kn->kn_hookid = vnode_vid(vp);
1682 kn->kn_filtid = EVFILTID_VN;
1683
1684 vnode_lock(vp);
1685 KNOTE_ATTACH(&vp->v_knotes, kn);
1686 result = filt_vnode_common(kn, vp, 0);
1687 vnode_unlock(vp);
1688
1689 /*
1690 * Ask the filesystem to provide remove notifications,
1691 * but ignore failure
1692 */
1693 VNOP_MONITOR(vp, 0, VNODE_MONITOR_BEGIN, (void*) kn, ctx);
1694 }
1695
1696 vnode_put(vp);
1697 }
1698
1699 out:
1700 if (error) {
1701 kn->kn_flags = EV_ERROR;
1702 kn->kn_data = error;
1703 }
1704
1705 return result;
1706 }
1707
1708 static void
1709 filt_vndetach(struct knote *kn)
1710 {
1711 vfs_context_t ctx = vfs_context_current();
1712 struct vnode *vp;
1713 vp = (struct vnode *)kn->kn_hook;
1714 if (vnode_getwithvid(vp, kn->kn_hookid))
1715 return;
1716
1717 vnode_lock(vp);
1718 KNOTE_DETACH(&vp->v_knotes, kn);
1719 vnode_unlock(vp);
1720
1721 /*
1722 * Tell a (generally networked) filesystem that we're no longer watching
1723 * If the FS wants to track contexts, it should still be using the one from
1724 * the VNODE_MONITOR_BEGIN.
1725 */
1726 VNOP_MONITOR(vp, 0, VNODE_MONITOR_END, (void*)kn, ctx);
1727 vnode_put(vp);
1728 }
1729
1730
1731 /*
1732 * Used for EVFILT_READ
1733 *
1734 * Takes only VFIFO or VREG. vnode is locked. We handle the "poll" case
1735 * differently than the regular case for VREG files. If not in poll(),
1736 * then we need to know current fileproc offset for VREG.
1737 */
1738 static intptr_t
1739 vnode_readable_data_count(vnode_t vp, off_t current_offset, int ispoll)
1740 {
1741 if (vnode_isfifo(vp)) {
1742 #if FIFO
1743 int cnt;
1744 int err = fifo_charcount(vp, &cnt);
1745 if (err == 0) {
1746 return (intptr_t)cnt;
1747 } else
1748 #endif
1749 {
1750 return (intptr_t)0;
1751 }
1752 } else if (vnode_isreg(vp)) {
1753 if (ispoll) {
1754 return (intptr_t)1;
1755 }
1756
1757 off_t amount;
1758 amount = vp->v_un.vu_ubcinfo->ui_size - current_offset;
1759 if (amount > (off_t)INTPTR_MAX) {
1760 return INTPTR_MAX;
1761 } else if (amount < (off_t)INTPTR_MIN) {
1762 return INTPTR_MIN;
1763 } else {
1764 return (intptr_t)amount;
1765 }
1766 } else {
1767 panic("Should never have an EVFILT_READ except for reg or fifo.");
1768 return 0;
1769 }
1770 }
1771
1772 /*
1773 * Used for EVFILT_WRITE.
1774 *
1775 * For regular vnodes, we can always write (1). For named pipes,
1776 * see how much space there is in the buffer. Nothing else is covered.
1777 */
1778 static intptr_t
1779 vnode_writable_space_count(vnode_t vp)
1780 {
1781 if (vnode_isfifo(vp)) {
1782 #if FIFO
1783 long spc;
1784 int err = fifo_freespace(vp, &spc);
1785 if (err == 0) {
1786 return (intptr_t)spc;
1787 } else
1788 #endif
1789 {
1790 return (intptr_t)0;
1791 }
1792 } else if (vnode_isreg(vp)) {
1793 return (intptr_t)1;
1794 } else {
1795 panic("Should never have an EVFILT_READ except for reg or fifo.");
1796 return 0;
1797 }
1798 }
1799
1800 /*
1801 * Determine whether this knote should be active
1802 *
1803 * This is kind of subtle.
1804 * --First, notice if the vnode has been revoked: in so, override hint
1805 * --EVFILT_READ knotes are checked no matter what the hint is
1806 * --Other knotes activate based on hint.
1807 * --If hint is revoke, set special flags and activate
1808 */
1809 static int
1810 filt_vnode_common(struct knote *kn, vnode_t vp, long hint)
1811 {
1812 int activate = 0;
1813
1814 lck_mtx_assert(&vp->v_lock, LCK_MTX_ASSERT_OWNED);
1815
1816 /* Special handling for vnodes that are in recycle or already gone */
1817 if (NOTE_REVOKE == hint) {
1818 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
1819 activate = 1;
1820
1821 if ((kn->kn_filter == EVFILT_VNODE) && (kn->kn_sfflags & NOTE_REVOKE)) {
1822 kn->kn_fflags |= NOTE_REVOKE;
1823 }
1824 } else {
1825 switch(kn->kn_filter) {
1826 case EVFILT_READ:
1827 kn->kn_data = vnode_readable_data_count(vp, kn->kn_fp->f_fglob->fg_offset, (kn->kn_flags & EV_POLL));
1828
1829 if (kn->kn_data != 0) {
1830 activate = 1;
1831 }
1832 break;
1833 case EVFILT_WRITE:
1834 kn->kn_data = vnode_writable_space_count(vp);
1835
1836 if (kn->kn_data != 0) {
1837 activate = 1;
1838 }
1839 break;
1840 case EVFILT_VNODE:
1841 /* Check events this note matches against the hint */
1842 if (kn->kn_sfflags & hint) {
1843 kn->kn_fflags |= hint; /* Set which event occurred */
1844 }
1845 if (kn->kn_fflags != 0) {
1846 activate = 1;
1847 }
1848 break;
1849 default:
1850 panic("Invalid knote filter on a vnode!\n");
1851 }
1852 }
1853 return (activate);
1854 }
1855
1856 static int
1857 filt_vnode(struct knote *kn, long hint)
1858 {
1859 vnode_t vp = (struct vnode *)kn->kn_hook;
1860
1861 return filt_vnode_common(kn, vp, hint);
1862 }
1863
1864 static int
1865 filt_vntouch(struct knote *kn, struct kevent_internal_s *kev)
1866 {
1867 vnode_t vp = (struct vnode *)kn->kn_hook;
1868 int activate;
1869 int hint = 0;
1870
1871 vnode_lock(vp);
1872 if (vnode_getiocount(vp, kn->kn_hookid, VNODE_NODEAD | VNODE_WITHID) != 0) {
1873 /* is recycled */
1874 hint = NOTE_REVOKE;
1875 }
1876
1877 /* accept new input fflags mask */
1878 kn->kn_sfflags = kev->fflags;
1879 if ((kn->kn_status & KN_UDATA_SPECIFIC) == 0)
1880 kn->kn_udata = kev->udata;
1881
1882 activate = filt_vnode_common(kn, vp, hint);
1883
1884 if (hint == 0)
1885 vnode_put_locked(vp);
1886 vnode_unlock(vp);
1887
1888 return activate;
1889 }
1890
1891 static int
1892 filt_vnprocess(struct knote *kn, struct filt_process_s *data, struct kevent_internal_s *kev)
1893 {
1894 #pragma unused(data)
1895 vnode_t vp = (struct vnode *)kn->kn_hook;
1896 int activate;
1897 int hint = 0;
1898
1899 vnode_lock(vp);
1900 if (vnode_getiocount(vp, kn->kn_hookid, VNODE_NODEAD | VNODE_WITHID) != 0) {
1901 /* Is recycled */
1902 hint = NOTE_REVOKE;
1903 }
1904 activate = filt_vnode_common(kn, vp, hint);
1905 if (activate) {
1906 *kev = kn->kn_kevent;
1907 if (kn->kn_flags & EV_CLEAR) {
1908 kn->kn_data = 0;
1909 kn->kn_fflags = 0;
1910 }
1911 }
1912
1913 /* Definitely need to unlock, may need to put */
1914 if (hint == 0)
1915 vnode_put_locked(vp);
1916 vnode_unlock(vp);
1917
1918 return activate;
1919 }
1920