xref: /xnu-11215.41.3/bsd/sys/file_internal.h (revision 33de042d024d46de5ff4e89f2471de6608e37fa4)
1 /*
2  * Copyright (c) 2000-2021 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, 1997 Apple 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  *
33  * Redistribution and use in source and binary forms, with or without
34  * modification, are permitted provided that the following conditions
35  * are met:
36  * 1. Redistributions of source code must retain the above copyright
37  *    notice, this list of conditions and the following disclaimer.
38  * 2. Redistributions in binary form must reproduce the above copyright
39  *    notice, this list of conditions and the following disclaimer in the
40  *    documentation and/or other materials provided with the distribution.
41  * 3. All advertising materials mentioning features or use of this software
42  *    must display the following acknowledgement:
43  *	This product includes software developed by the University of
44  *	California, Berkeley and its contributors.
45  * 4. Neither the name of the University nor the names of its contributors
46  *    may be used to endorse or promote products derived from this software
47  *    without specific prior written permission.
48  *
49  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59  * SUCH DAMAGE.
60  *
61  *	@(#)file.h	8.3 (Berkeley) 1/9/95
62  */
63 
64 #ifndef _SYS_FILE_INTERNAL_H_
65 #define _SYS_FILE_INTERNAL_H_
66 
67 #include <sys/appleapiopts.h>
68 #include <sys/fcntl.h>
69 #include <sys/unistd.h>
70 
71 #ifdef XNU_KERNEL_PRIVATE
72 #include <sys/errno.h>
73 #include <sys/queue.h>
74 #include <sys/cdefs.h>
75 #include <sys/constrained_ctypes.h>
76 #include <sys/lock.h>
77 #include <sys/file.h>
78 #include <sys/filedesc.h>
79 #include <sys/guarded.h>
80 #include <os/refcnt.h>
81 
82 __BEGIN_DECLS
83 
84 #pragma GCC visibility push(hidden)
85 
86 struct proc;
87 struct uio;
88 struct knote;
89 struct kevent_qos_s;
90 struct file;
91 #ifndef _KAUTH_CRED_T
92 #define _KAUTH_CRED_T
93 typedef struct ucred *kauth_cred_t;
94 typedef struct posix_cred *posix_cred_t;
95 #endif  /* !_KAUTH_CRED_T */
96 
97 __options_decl(fileproc_vflags_t, unsigned int, {
98 	FPV_NONE        = 0,
99 	FPV_DRAIN       = 0x01,
100 });
101 
102 __options_decl(fileproc_flags_t, uint16_t, {
103 	FP_NONE         = 0,
104 	FP_CLOEXEC      = 0x01,
105 	FP_CLOFORK      = 0x02,
106 	FP_INSELECT     = 0x04,
107 	FP_AIOISSUED    = 0x08,
108 	FP_SELCONFLICT  = 0x10,  /* select conflict on an individual fp */
109 });
110 
111 struct fileproc_guard {
112 	struct select_set *fpg_wset;
113 	guardid_t         fpg_guard;
114 };
115 
116 /*
117  * Kernel descriptor table.
118  * One entry for each open kernel vnode and socket.
119  */
120 struct fileproc {
121 	os_refcnt_t      fp_iocount;
122 	_Atomic fileproc_vflags_t fp_vflags;
123 	fileproc_flags_t fp_flags;
124 	uint16_t         fp_guard_attrs;
125 	struct fileglob *XNU_PTRAUTH_SIGNED_PTR("fileproc.fp_glob") fp_glob;
126 	union {
127 		struct select_set     *fp_wset;   /* fp_guard_attrs == 0 */
128 		struct fileproc_guard *XNU_PTRAUTH_SIGNED_PTR("fileproc.fp_guard") fp_guard;  /* fp_guard_attrs != 0 */
129 	};
130 };
131 __CCT_DECLARE_CONSTRAINED_PTR_TYPES(struct fileproc, fileproc);
132 #define FILEPROC_NULL ((struct fileproc *)0)
133 
134 /* file types */
135 typedef enum {
136 	DTYPE_VNODE     = 1,    /* file */
137 	DTYPE_SOCKET,           /* communications endpoint */
138 	DTYPE_PSXSHM,           /* POSIX Shared memory */
139 	DTYPE_PSXSEM,           /* POSIX Semaphores */
140 	DTYPE_KQUEUE,           /* kqueue */
141 	DTYPE_PIPE,             /* pipe */
142 	DTYPE_FSEVENTS,         /* fsevents */
143 	DTYPE_ATALK,            /* (obsolete) */
144 	DTYPE_NETPOLICY,        /* networking policy */
145 	DTYPE_CHANNEL,          /* Skywalk Channel */
146 	DTYPE_NEXUS             /* Skywalk Nexus */
147 } file_type_t;
148 
149 /* defines for fg_lflags */
150 // was  FG_TERM         0x01
151 #define FG_INSMSGQ      0x02    /* insert to msgqueue pending .. */
152 #define FG_WINSMSGQ     0x04    /* wait for the fielglob is in msgque */
153 #define FG_RMMSGQ       0x08    /* the fileglob is being removed from msgqueue */
154 #define FG_WRMMSGQ      0x10    /* wait for the fileglob to  be removed from msgqueue */
155 #define FG_PORTMADE     0x20    /* a port was at some point created for this fileglob */
156 #define FG_NOSIGPIPE    0x40    /* don't deliver SIGPIPE with EPIPE return */
157 #define FG_OFF_LOCKED   0x80    /* Used as a mutex for offset changes (for vnodes) */
158 #define FG_OFF_LOCKWANT 0x100   /* Somebody's wating for the lock */
159 #define FG_CONFINED     0x200   /* fileglob confined to process, immutably */
160 #define FG_HAS_OFDLOCK  0x400   /* Has or has had an OFD lock */
161 
162 struct fileops {
163 	file_type_t     fo_type;        /* descriptor type */
164 	int (*fo_read)      (struct fileproc *fp, struct uio *uio,
165 	    int flags, vfs_context_t ctx);
166 	int (*fo_write)     (struct fileproc *fp, struct uio *uio,
167 	    int flags, vfs_context_t ctx);
168 #define FOF_OFFSET      0x00000001      /* offset supplied to vn_write */
169 	int (*fo_ioctl)(struct fileproc *fp, u_long com,
170 	    caddr_t data, vfs_context_t ctx);
171 	int (*fo_select)    (struct fileproc *fp, int which,
172 	    void *wql, vfs_context_t ctx);
173 	int (*fo_close)     (struct fileglob *fg, vfs_context_t ctx);
174 	int (*fo_kqfilter)  (struct fileproc *fp, struct knote *, struct kevent_qos_s *);
175 	int (*fo_drain)     (struct fileproc *fp, vfs_context_t ctx);
176 };
177 
178 struct fileglob {
179 	LIST_ENTRY(fileglob) f_msglist;     /* list of files in unix messages */
180 	uint32_t             fg_flag;       /* (atomic) see fcntl.h */
181 	os_ref_atomic_t      fg_count;      /* reference count */
182 	uint32_t             fg_msgcount;   /* references from message queue */
183 	int32_t              fg_lflags;     /* file global flags */
184 	kauth_cred_t         XNU_PTRAUTH_SIGNED_PTR("fileglob.fg_cred") fg_cred;        /* credentials associated with descriptor */
185 	const struct fileops *XNU_PTRAUTH_SIGNED_PTR("fileglob.fg_ops") fg_ops;
186 	off_t                fg_offset;
187 	uintptr_t            fg_data;       /* vnode or socket or SHM or semaphore */
188 	struct fd_vn_data   *XNU_PTRAUTH_SIGNED_PTR("fileglob.fg_vn_data") fg_vn_data;  /* Per fd vnode data, used for directories */
189 	lck_mtx_t            fg_lock;
190 #if CONFIG_MACF && CONFIG_VNGUARD
191 	struct vng_owner    *fg_vgo;        /* Used by the vnode guard MAC hook */
192 #endif
193 };
194 
195 /* Disambiguate OFD ids from flock ids (fileglobs) */
196 __pure2
197 static inline caddr_t __unsafe_indexable
ofd_to_id(const struct fileglob * fg)198 ofd_to_id(const struct fileglob *fg)
199 {
200 	return (caddr_t __unsafe_indexable)~(uintptr_t)fg;
201 }
202 
203 extern int maxfiles;                    /* kernel limit on number of open files */
204 extern int nfiles;                      /* actual number of open files */
205 extern int maxfilesperproc;
206 os_refgrp_decl_extern(f_refgrp);        /* os_refgrp_t for file refcounts */
207 
208 #define FILEGLOB_DTYPE(fg)              ((const file_type_t)((fg)->fg_ops->fo_type))
209 
210 /* Special value to indicate "no process association". */
211 #define FG_NOPROC       ((struct proc *)~0UL)
212 
213 #pragma mark files (struct fileglob)
214 
215 /*!
216  * @function fg_alloc_init
217  *
218  * @brief
219  * Allocate and minimally initialize a file structure.
220  *
221  * @description
222  * The fileglob is allocated as if with falloc_withinit(), but is not
223  * assocated with any fileproc.
224  */
225 struct fileglob *
226 fg_alloc_init(vfs_context_t ctx);
227 
228 /*!
229  * @function fg_ref
230  *
231  * @brief
232  * Acquire a file reference on the specified file.
233  *
234  * @description
235  * The @c proc must be locked while this operation is being performed
236  * to avoid races with setting the FG_CONFINED flag.
237  *
238  * @param proc
239  * The proc this file reference is taken on behalf of, or FG_NOPROC
240  * if the file is guaranteed to not be associated with any fileproc.
241  *
242  * @param fg
243  * The specified file
244  */
245 void
246 fg_ref(proc_t proc, struct fileglob *fg);
247 
248 /*!
249  * @function fg_drop_live
250  *
251  * @brief
252  * Drops a file reference on the specified file that isn't the last one.
253  *
254  * @param fg
255  * The file whose reference is being dropped.
256  */
257 void
258 fg_drop_live(struct fileglob *fg);
259 
260 /*!
261  * @function fg_drop
262  *
263  * @brief
264  * Drops a file reference on the specified file.
265  *
266  * @discussion
267  * No locks should be held when calling this function.
268  *
269  * @param p
270  * The process making the request,
271  * or FG_NOPROC if the file belongs to a message/fileport.
272  *
273  * @param fg
274  * The file being closed.
275  *
276  * @returns
277  * 0          Success
278  * ???        Any error that @c fileops::fo_close can return
279  */
280 int
281 fg_drop(proc_t p, struct fileglob *fg);
282 
283 /*!
284  * @function fg_sendable
285  *
286  * @brief
287  * Returns whether a particular file can be sent over IPC.
288  */
289 bool
290 fg_sendable(struct fileglob *fg);
291 
292 /*!
293  * @function fg_get_data_volatile
294  *
295  * @brief
296  * Returns the fileglob opaque data pointer.
297  *
298  * @discussion
299  * Unlike @c fg_get_data() this variant will
300  * not be hoisted by the compiler.
301  *
302  * @param fg
303  * The file whose data is being requested.
304  */
305 void *
306 fg_get_data_volatile(struct fileglob *fg);
307 
308 /*!
309  * @function fg_get_data
310  *
311  * @brief
312  * Returns the fileglob opaque data pointer.
313  *
314  * @discussion
315  * Unlike @c fg_get_data_volatile() this variant
316  * will be hoisted by the compiler if it is called
317  * repeatedly.
318  *
319  * @param fg
320  * The file whose data is being requested.
321  */
322 __pure2
323 static inline void *
fg_get_data(struct fileglob * fg)324 fg_get_data(struct fileglob *fg)
325 {
326 	return fg_get_data_volatile(fg);
327 }
328 
329 /*!
330  * @function fg_set_data
331  *
332  * @brief
333  * Sets the fileglob opaque data pointer.
334  *
335  * @param fg
336  * The file whose data is being set.
337  *
338  * @param fg_data
339  * Opaque file data value
340  */
341 void
342 fg_set_data(struct fileglob *fg, void *fg_data);
343 
344 #pragma mark file descriptor entries (struct fileproc)
345 
346 /*!
347  * @function fg_get_data
348  *
349  * @brief
350  * Returns the fileproc fileglob opaque data pointer.
351  *
352  * @discussion
353  * Unlike @c fp_get_data_volatile() this variant
354  * will be hoisted by the compiler if it is called
355  * repeatedly.
356  *
357  * @param fp
358  * The fileproc whose data is being requested.
359  */
360 __pure2
361 static inline void *
fp_get_data(struct fileproc * fp)362 fp_get_data(struct fileproc *fp)
363 {
364 	return fg_get_data(fp->fp_glob);
365 }
366 
367 /*!
368  * @function fp_get_data
369  *
370  * @brief
371  * Returns the fileproc fileglob opaque data pointer.
372  *
373  * @discussion
374  * Unlike @c fp_get_data() this variant will
375  * not be hoisted by the compiler.
376  *
377  * @param fp
378  * The fileproc whose data is being requested.
379  */
380 static inline void *
fp_get_data_volatile(struct fileproc * fp)381 fp_get_data_volatile(struct fileproc *fp)
382 {
383 	return fg_get_data_volatile(fp->fp_glob);
384 }
385 
386 /*!
387  * @function fp_set_data
388  *
389  * @brief
390  * Sets the fileproc opaque data pointer.
391  *
392  * @param fp
393  * The fileproc whose data is being set.
394  *
395  * @param fg_data
396  * Opaque file data value
397  */
398 static inline void
fp_set_data(struct fileproc * fp,void * fg_data)399 fp_set_data(struct fileproc *fp, void *fg_data)
400 {
401 	fg_set_data(fp->fp_glob, fg_data);
402 }
403 
404 /*!
405  * @function fp_get_ftype
406  *
407  * @brief
408  * Get the fileproc pointer for the given fd from the per process, with the
409  * specified file type, and with an I/O reference.
410  *
411  * @param p
412  * The process in which fd lives.
413  *
414  * @param fd
415  * The file descriptor index to lookup.
416  *
417  * @param ftype
418  * The required file type.
419  *
420  * @param err
421  * The error to return if the file exists but isn't of the specified type.
422  *
423  * @param fpp
424  * The returned fileproc when the call returns 0.
425  *
426  * @returns
427  * 0            Success (@c fpp is set)
428  * EBADF        Bad file descriptor
429  * @c err       There is an entry, but it isn't of the specified type.
430  */
431 extern int
432 fp_get_ftype(proc_t p, int fd, file_type_t ftype, int err, struct fileproc **fpp);
433 
434 /*!
435  * @function fp_get_noref_locked
436  *
437  * @brief
438  * Get the fileproc pointer for the given fd from the per process
439  * open file table without taking an explicit reference on it.
440  *
441  * @description
442  * This function assumes that the @c proc_fdlock is held, as the caller
443  * doesn't hold an I/O reference for the returned fileproc.
444  *
445  * Because there is no reference explicitly taken, the returned
446  * fileproc pointer is only valid so long as the @c proc_fdlock
447  * remains held by the caller.
448  *
449  * @param p
450  * The process in which fd lives.
451  *
452  * @param fd
453  * The file descriptor index to lookup.
454  *
455  * @returns
456  * - the fileproc on success
457  * - FILEPROC_NULL on error
458  */
459 extern struct fileproc *
460 fp_get_noref_locked(proc_t p, int fd);
461 
462 /*!
463  * @function fp_get_noref_locked_with_iocount
464  *
465  * @brief
466  * Similar to fp_get_noref_locked(), but allows returning files that are
467  * closing.
468  *
469  * @discussion
470  * Some parts of the kernel take I/O references on fileprocs but only remember
471  * the file descriptor for which they did that.
472  *
473  * These interfaces later need to drop that reference, but if the file is
474  * already closing, then fp_get_noref_locked() will refuse to resolve
475  * the file descriptor.
476  *
477  * This interface allows the lookup (but will assert that the fileproc has
478  * enouhg I/O references).
479  *
480  * @warning
481  * New code should NOT use this function, it is required for interfaces
482  * that acquire iocounts without remembering the fileproc pointer,
483  * which is bad practice.
484  */
485 extern struct fileproc *
486 fp_get_noref_locked_with_iocount(proc_t p, int fd);
487 
488 /*!
489  * @function fp_close_and_unlock
490  *
491  * @brief
492  * Close the given file descriptor entry.
493  *
494  * @description
495  * This function assumes that the @c proc_fdlock is held,
496  * and that the caller holds no additional I/O reference
497  * on the specified file descriptor entry.
498  *
499  * The @c proc_fdlock is unlocked upon return.
500  *
501  * @param p             The process in which fd lives.
502  * @param p_cred        The proc's cred for this operation.
503  * @param fd            The file descriptor index being closed.
504  * @param fp            The fileproc entry associated with @c fd.
505  * @param flags         FD_DUP2RESV or 0.
506  *
507  * @returns
508  * 0            Success
509  * EBADF        Bad file descriptor
510  * ???          Any error that @c fileops::fo_close can return.
511  */
512 extern int
513 fp_close_and_unlock(proc_t p, kauth_cred_t p_cred, int fd, struct fileproc *fp, int flags);
514 
515 /* wrappers for fp->f_ops->fo_... */
516 int fo_read(struct fileproc *fp, struct uio *uio, int flags, vfs_context_t ctx);
517 int fo_write(struct fileproc *fp, struct uio *uio, int flags,
518     vfs_context_t ctx);
519 int fo_ioctl(struct fileproc *fp, u_long com, caddr_t data, vfs_context_t ctx);
520 int fo_select(struct fileproc *fp, int which, void *wql, vfs_context_t ctx);
521 int fo_close(struct fileglob *fg, vfs_context_t ctx);
522 int fo_drain(struct fileproc *fp, vfs_context_t ctx);
523 int fo_kqfilter(struct fileproc *fp, struct knote *kn, struct kevent_qos_s *kev);
524 
525 /* Functions to use for unsupported fileops */
526 int fo_no_read(struct fileproc *fp, struct uio *uio, int flags, vfs_context_t ctx);
527 int fo_no_write(struct fileproc *fp, struct uio *uio, int flags,
528     vfs_context_t ctx);
529 int fo_no_ioctl(struct fileproc *fp, u_long com, caddr_t data, vfs_context_t ctx);
530 int fo_no_select(struct fileproc *fp, int which, void *wql, vfs_context_t ctx);
531 int fo_no_drain(struct fileproc *fp, vfs_context_t ctx);
532 int fo_no_kqfilter(struct fileproc *, struct knote *, struct kevent_qos_s *kev);
533 
534 int fp_tryswap(proc_t, int fd, struct fileproc *nfp);
535 int fp_drop(struct proc *p, int fd, struct fileproc *fp, int locked);
536 void fp_free(struct proc * p, int fd, struct fileproc * fp);
537 int fp_lookup(struct proc *p, int fd, struct fileproc **resultfp, int locked);
538 int fp_lookup_guarded(struct proc *p, int fd, guardid_t guard, struct fileproc **resultfp, int locked);
539 int fp_isguarded(struct fileproc *fp, u_int attribs);
540 int fp_guard_exception(proc_t p, int fd, struct fileproc *fp, u_int attribs);
541 struct nameidata;
542 struct vnode_attr;
543 int open1(vfs_context_t ctx, struct nameidata *ndp, int uflags,
544     struct vnode_attr *vap, fp_initfn_t fp_init, void *initarg,
545     int32_t *retval, int authfd);
546 int chdir_internal(proc_t p, vfs_context_t ctx, struct nameidata *ndp, int per_thread);
547 int kqueue_internal(struct proc *p, fp_initfn_t, void *initarg, int32_t *retval);
548 void procfdtbl_releasefd(struct proc * p, int fd, struct fileproc * fp);
549 extern struct fileproc *fileproc_alloc_init(void);
550 extern void fileproc_free(struct fileproc *fp);
551 extern void guarded_fileproc_copy_guard(struct fileproc *ofp, struct fileproc *nfp);
552 extern void guarded_fileproc_unguard(struct fileproc *fp);
553 extern void fg_vn_data_free(void *fgvndata);
554 extern int nameiat(struct nameidata *ndp, int dirfd);
555 extern void vn_offset_lock(struct fileglob *fg);
556 extern void vn_offset_unlock(struct fileglob *fg);
557 extern int falloc_guarded(struct proc *p, struct fileproc **fp, int *fd,
558     vfs_context_t ctx, const guardid_t *guard, u_int attrs);
559 extern void fileproc_modify_vflags(struct fileproc *fp, fileproc_vflags_t vflags, boolean_t clearflags);
560 fileproc_vflags_t fileproc_get_vflags(struct fileproc *fp);
561 
562 #pragma mark internal version of syscalls
563 
564 int fileport_makefd(proc_t p, ipc_port_t port, fileproc_flags_t fp_flags, int *fd);
565 int dup2(proc_t p, kauth_cred_t p_cred, int from, int to, int *fd);
566 int close_nocancel(proc_t p, kauth_cred_t p_cred, int fd);
567 int fchdir(proc_t p, vfs_context_t ctx, int fd, bool per_thread);
568 
569 #pragma GCC visibility pop
570 
571 __END_DECLS
572 
573 #endif /* XNU_KERNEL_PRIVATE */
574 
575 #endif /* !_SYS_FILE_INTERNAL_H_ */
576