xref: /xnu-10002.61.3/bsd/kern/posix_sem.c (revision 0f4c859e951fba394238ab619495c4e1d54d0f34)
1 /*
2  * Copyright (c) 2000-2007 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 /*
29  *	Copyright (c) 1990, 1996-1998 Apple Computer, Inc.
30  *	All Rights Reserved.
31  */
32 /*
33  * posix_sem.c : Support for POSIX semaphore APIs
34  *
35  *	File:	posix_sem.c
36  *	Author:	Ananthakrishna Ramesh
37  *
38  * HISTORY
39  * 2-Sep-1999	A.Ramesh
40  *	Created for MacOSX
41  *
42  */
43 /*
44  * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
45  * support for mandatory and extensible security protections.  This notice
46  * is included in support of clause 2.2 (b) of the Apple Public License,
47  * Version 2.0.
48  */
49 
50 #include <sys/cdefs.h>
51 #include <sys/param.h>
52 #include <sys/systm.h>
53 #include <sys/kernel.h>
54 #include <sys/file_internal.h>
55 #include <sys/filedesc.h>
56 #include <sys/stat.h>
57 #include <sys/proc_internal.h>
58 #include <sys/kauth.h>
59 #include <sys/mount.h>
60 #include <sys/namei.h>
61 #include <sys/vnode.h>
62 #include <sys/ioctl.h>
63 #include <sys/tty.h>
64 #include <sys/malloc.h>
65 #include <sys/semaphore.h>
66 #include <sys/sysproto.h>
67 #include <sys/proc_info.h>
68 
69 #if CONFIG_MACF
70 #include <sys/vnode_internal.h>
71 #include <security/mac_framework.h>
72 #endif
73 
74 #include <security/audit/audit.h>
75 
76 #include <mach/mach_types.h>
77 #include <mach/vm_prot.h>
78 #include <mach/semaphore.h>
79 #include <mach/sync_policy.h>
80 #include <mach/task.h>
81 #include <kern/kern_types.h>
82 #include <kern/task.h>
83 #include <kern/clock.h>
84 #include <mach/kern_return.h>
85 
86 #define f_flag fp_glob->fg_flag
87 #define f_ops fp_glob->fg_ops
88 
89 #define PSEMNAMLEN      31      /* maximum name segment length we bother with */
90 
91 struct pseminfo {
92 	unsigned int    psem_flags;
93 	unsigned int    psem_usecount;
94 	mode_t          psem_mode;
95 	uid_t           psem_uid;
96 	gid_t           psem_gid;
97 	char            psem_name[PSEMNAMLEN + 1];      /* segment name */
98 	semaphore_t     psem_semobject;
99 	struct label *  psem_label;
100 	pid_t           psem_creator_pid;
101 	uint64_t        psem_creator_uniqueid;
102 };
103 #define PSEMINFO_NULL (struct pseminfo *)0
104 
105 #define PSEM_NONE       1
106 #define PSEM_DEFINED    2
107 #define PSEM_ALLOCATED  4
108 #define PSEM_MAPPED     8
109 #define PSEM_INUSE      0x10
110 #define PSEM_REMOVED    0x20
111 #define PSEM_INCREATE   0x40
112 #define PSEM_INDELETE   0x80
113 
114 struct  psemcache {
115 	LIST_ENTRY(psemcache) psem_hash;        /* hash chain */
116 	struct  pseminfo *pseminfo;             /* vnode the name refers to */
117 	size_t  psem_nlen;              /* length of name */
118 	char    psem_name[PSEMNAMLEN + 1];      /* segment name */
119 };
120 #define PSEMCACHE_NULL (struct psemcache *)0
121 
122 #define PSEMCACHE_NOTFOUND (0)
123 #define PSEMCACHE_FOUND    (-1)
124 #define PSEMCACHE_NEGATIVE (ENOENT)
125 
126 struct  psemstats {
127 	long    goodhits;               /* hits that we can really use */
128 	long    neghits;                /* negative hits that we can use */
129 	long    badhits;                /* hits we must drop */
130 	long    falsehits;              /* hits with id mismatch */
131 	long    miss;           /* misses */
132 	long    longnames;              /* long names that ignore cache */
133 };
134 
135 struct psemname {
136 	char    *psem_nameptr;  /* pointer to looked up name */
137 	size_t  psem_namelen;   /* length of looked up component */
138 	u_int32_t       psem_hash;      /* hash value of looked up name */
139 };
140 
141 struct psemnode {
142 	struct pseminfo *pinfo;
143 #if DIAGNOSTIC
144 	unsigned int readcnt;
145 	unsigned int writecnt;
146 #endif
147 };
148 #define PSEMNODE_NULL (struct psemnode *)0
149 
150 
151 #define PSEMHASH(pnp) \
152 	(&psemhashtbl[(pnp)->psem_hash & psemhash])
153 LIST_HEAD(psemhashhead, psemcache) * psemhashtbl;        /* Hash Table */
154 u_long  psemhash;                               /* size of hash table - 1 */
155 long    psemnument;                     /* number of cache entries allocated */
156 long    posix_sem_max = 10000;          /* tunable for max POSIX semaphores */
157                                         /* 10000 limits to ~1M of memory */
158 SYSCTL_NODE(_kern, KERN_POSIX, posix, CTLFLAG_RW | CTLFLAG_LOCKED, 0, "Posix");
159 SYSCTL_NODE(_kern_posix, OID_AUTO, sem, CTLFLAG_RW | CTLFLAG_LOCKED, 0, "Semaphores");
160 SYSCTL_LONG(_kern_posix_sem, OID_AUTO, max, CTLFLAG_RW | CTLFLAG_LOCKED, &posix_sem_max, "max");
161 
162 struct psemstats psemstats;             /* cache effectiveness statistics */
163 
164 static int psem_access(struct pseminfo *pinfo, mode_t mode, kauth_cred_t cred);
165 static int psem_cache_search(struct pseminfo **,
166     struct psemname *, struct psemcache **);
167 static int psem_delete(struct pseminfo * pinfo);
168 
169 static int psem_closefile(struct fileglob *fp, vfs_context_t ctx);
170 static int psem_unlink_internal(struct pseminfo *pinfo, struct psemcache *pcache);
171 
172 static const struct fileops psemops = {
173 	.fo_type     = DTYPE_PSXSEM,
174 	.fo_read     = fo_no_read,
175 	.fo_write    = fo_no_write,
176 	.fo_ioctl    = fo_no_ioctl,
177 	.fo_select   = fo_no_select,
178 	.fo_close    = psem_closefile,
179 	.fo_drain    = fo_no_drain,
180 	.fo_kqfilter = fo_no_kqfilter,
181 };
182 
183 static LCK_GRP_DECLARE(psx_sem_subsys_lck_grp, "posix semaphores");
184 static LCK_MTX_DECLARE(psx_sem_subsys_mutex, &psx_sem_subsys_lck_grp);
185 
186 #define PSEM_SUBSYS_LOCK() lck_mtx_lock(&psx_sem_subsys_mutex)
187 #define PSEM_SUBSYS_UNLOCK() lck_mtx_unlock(&psx_sem_subsys_mutex)
188 #define PSEM_SUBSYS_ASSERT_HELD() LCK_MTX_ASSERT(&psx_sem_subsys_mutex, LCK_MTX_ASSERT_OWNED)
189 
190 
191 static int psem_cache_add(struct pseminfo *psemp, struct psemname *pnp, struct psemcache *pcp);
192 static void psem_cache_delete(struct psemcache *pcp);
193 int psem_cache_purge_all(void);
194 
195 /*
196  * Lookup an entry in the cache
197  *
198  *
199  * status of -1 is returned if matches
200  * If the lookup determines that the name does not exist
201  * (negative cacheing), a status of ENOENT is returned. If the lookup
202  * fails, a status of zero is returned.
203  */
204 
205 static int
psem_cache_search(struct pseminfo ** psemp,struct psemname * pnp,struct psemcache ** pcache)206 psem_cache_search(struct pseminfo **psemp, struct psemname *pnp,
207     struct psemcache **pcache)
208 {
209 	struct psemcache *pcp, *nnp;
210 	struct psemhashhead *pcpp;
211 
212 	if (pnp->psem_namelen > PSEMNAMLEN) {
213 		psemstats.longnames++;
214 		return PSEMCACHE_NOTFOUND;
215 	}
216 
217 	pcpp = PSEMHASH(pnp);
218 	for (pcp = pcpp->lh_first; pcp != 0; pcp = nnp) {
219 		nnp = pcp->psem_hash.le_next;
220 		if (pcp->psem_nlen == pnp->psem_namelen &&
221 		    !bcmp(pcp->psem_name, pnp->psem_nameptr, pcp->psem_nlen)) {
222 			break;
223 		}
224 	}
225 
226 	if (pcp == 0) {
227 		psemstats.miss++;
228 		return PSEMCACHE_NOTFOUND;
229 	}
230 
231 	/* We found a "positive" match, return the vnode */
232 	if (pcp->pseminfo) {
233 		psemstats.goodhits++;
234 		/* TOUCH(ncp); */
235 		*psemp = pcp->pseminfo;
236 		*pcache = pcp;
237 		return PSEMCACHE_FOUND;
238 	}
239 
240 	/*
241 	 * We found a "negative" match, ENOENT notifies client of this match.
242 	 * The nc_vpid field records whether this is a whiteout.
243 	 */
244 	psemstats.neghits++;
245 	return PSEMCACHE_NEGATIVE;
246 }
247 
248 /*
249  * Add an entry to the cache.
250  */
251 static int
psem_cache_add(struct pseminfo * psemp,struct psemname * pnp,struct psemcache * pcp)252 psem_cache_add(struct pseminfo *psemp, struct psemname *pnp, struct psemcache *pcp)
253 {
254 	struct psemhashhead *pcpp;
255 	struct pseminfo *dpinfo;
256 	struct psemcache *dpcp;
257 
258 #if DIAGNOSTIC
259 	if (pnp->psem_namelen > PSEMNAMLEN) {
260 		panic("cache_enter: name too long");
261 	}
262 #endif
263 
264 
265 	/*  if the entry has already been added by some one else return */
266 	if (psem_cache_search(&dpinfo, pnp, &dpcp) == PSEMCACHE_FOUND) {
267 		return EEXIST;
268 	}
269 	if (psemnument >= posix_sem_max) {
270 		return ENOSPC;
271 	}
272 	psemnument++;
273 	/*
274 	 * Fill in cache info, if vp is NULL this is a "negative" cache entry.
275 	 * For negative entries, we have to record whether it is a whiteout.
276 	 * the whiteout flag is stored in the nc_vpid field which is
277 	 * otherwise unused.
278 	 */
279 	pcp->pseminfo = psemp;
280 	pcp->psem_nlen = pnp->psem_namelen;
281 	bcopy(pnp->psem_nameptr, pcp->psem_name, pcp->psem_nlen);
282 	pcpp = PSEMHASH(pnp);
283 #if DIAGNOSTIC
284 	{
285 		struct psemcache *p;
286 
287 		for (p = pcpp->lh_first; p != 0; p = p->psem_hash.le_next) {
288 			if (p == pcp) {
289 				panic("psem:cache_enter duplicate");
290 			}
291 		}
292 	}
293 #endif
294 	LIST_INSERT_HEAD(pcpp, pcp, psem_hash);
295 	return 0;
296 }
297 
298 /*
299  * Name cache initialization, from vfs_init() when we are booting
300  */
301 void
psem_cache_init(void)302 psem_cache_init(void)
303 {
304 	psemhashtbl = hashinit((int)(posix_sem_max / 2), M_SHM, &psemhash);
305 }
306 
307 static void
psem_cache_delete(struct psemcache * pcp)308 psem_cache_delete(struct psemcache *pcp)
309 {
310 #if DIAGNOSTIC
311 	if (pcp->psem_hash.le_prev == 0) {
312 		panic("psem namecache purge le_prev");
313 	}
314 	if (pcp->psem_hash.le_next == pcp) {
315 		panic("namecache purge le_next");
316 	}
317 #endif /* DIAGNOSTIC */
318 	LIST_REMOVE(pcp, psem_hash);
319 	pcp->psem_hash.le_prev = NULL;
320 	psemnument--;
321 }
322 
323 /*
324  * Remove all cached psem entries. Open semaphores (with a positive refcount)
325  * will continue to exist, but their cache entries tying them to a particular
326  * name/path will be removed making all future lookups on the name fail.
327  */
328 int
psem_cache_purge_all(void)329 psem_cache_purge_all(void)
330 {
331 	struct psemcache *pcp, *tmppcp;
332 	struct psemhashhead *pcpp;
333 	int error = 0;
334 
335 	if (kauth_cred_issuser(kauth_cred_get()) == 0) {
336 		return EPERM;
337 	}
338 
339 	PSEM_SUBSYS_LOCK();
340 	for (pcpp = &psemhashtbl[psemhash]; pcpp >= psemhashtbl; pcpp--) {
341 		LIST_FOREACH_SAFE(pcp, pcpp, psem_hash, tmppcp) {
342 			assert(pcp->psem_nlen);
343 			/*
344 			 * unconditionally unlink the cache entry
345 			 */
346 			error = psem_unlink_internal(pcp->pseminfo, pcp);
347 			if (error) {
348 				goto out;
349 			}
350 		}
351 	}
352 	assert(psemnument == 0);
353 
354 out:
355 	PSEM_SUBSYS_UNLOCK();
356 
357 	if (error) {
358 		printf("%s: Error %d removing all semaphores: %ld remain!\n",
359 		    __func__, error, psemnument);
360 	}
361 	return error;
362 }
363 
364 /*
365  *		In order to support unnamed POSIX semaphores, the named
366  *		POSIX semaphores will have to move out of the per-process
367  *		open filetable, and into a global table that is shared with
368  *		unnamed POSIX semaphores, since unnamed POSIX semaphores
369  *		are typically used by declaring instances in shared memory,
370  *		and there's no other way to do this without changing the
371  *		underlying type, which would introduce binary compatibility
372  *		issues.
373  */
374 int
sem_open(proc_t p,struct sem_open_args * uap,user_addr_t * retval)375 sem_open(proc_t p, struct sem_open_args *uap, user_addr_t *retval)
376 {
377 	size_t i;
378 	int indx, error;
379 	struct psemname nd;
380 	struct pseminfo *pinfo;
381 	struct fileproc *fp = NULL;
382 	char *pnbuf = NULL;
383 	struct pseminfo *new_pinfo = PSEMINFO_NULL;
384 	struct psemnode *new_pnode = PSEMNODE_NULL;
385 	struct psemcache *pcache = PSEMCACHE_NULL;
386 	char * nameptr;
387 	char * cp;
388 	size_t pathlen, plen;
389 	mode_t fmode;
390 	mode_t cmode = (mode_t)uap->mode;
391 	int value = uap->value;
392 	int incache = 0;
393 	struct psemcache *pcp = PSEMCACHE_NULL;
394 	kern_return_t kret = KERN_INVALID_ADDRESS;      /* default fail */
395 
396 	AUDIT_ARG(fflags, uap->oflag);
397 	AUDIT_ARG(mode, (mode_t)uap->mode);
398 	AUDIT_ARG(value32, uap->value);
399 
400 	pinfo = PSEMINFO_NULL;
401 
402 	/*
403 	 * Preallocate everything we might need up front to avoid taking
404 	 * and dropping the lock, opening us up to race conditions.
405 	 */
406 	pnbuf = zalloc_flags(ZV_NAMEI, Z_WAITOK | Z_ZERO);
407 
408 	pathlen = MAXPATHLEN;
409 	error = copyinstr(uap->name, pnbuf, MAXPATHLEN, &pathlen);
410 	if (error) {
411 		goto bad;
412 	}
413 	AUDIT_ARG(text, pnbuf);
414 	if ((pathlen > PSEMNAMLEN)) {
415 		error = ENAMETOOLONG;
416 		goto bad;
417 	}
418 
419 #ifdef PSXSEM_NAME_RESTRICT
420 	nameptr = pnbuf;
421 	if (*nameptr == '/') {
422 		while (*(nameptr++) == '/') {
423 			plen--;
424 			error = EINVAL;
425 			goto bad;
426 		}
427 	} else {
428 		error = EINVAL;
429 		goto bad;
430 	}
431 #endif /* PSXSEM_NAME_RESTRICT */
432 
433 	plen = pathlen;
434 	nameptr = pnbuf;
435 	nd.psem_nameptr = nameptr;
436 	nd.psem_namelen = plen;
437 	nd.psem_hash = 0;
438 
439 	for (cp = nameptr, i = 1; *cp != 0 && i <= plen; i++, cp++) {
440 		nd.psem_hash += (unsigned char)*cp * i;
441 	}
442 
443 	/*
444 	 * attempt to allocate a new fp; if unsuccessful, the fp will be
445 	 * left unmodified (NULL).
446 	 */
447 	error = falloc(p, &fp, &indx, vfs_context_current());
448 	if (error) {
449 		goto bad;
450 	}
451 
452 	/*
453 	 * We allocate a new entry if we are less than the maximum
454 	 * allowed and the one at the front of the LRU list is in use.
455 	 * Otherwise we use the one at the front of the LRU list.
456 	 */
457 	pcp = kalloc_type(struct psemcache, Z_WAITOK | Z_ZERO | Z_NOFAIL);
458 	new_pinfo = kalloc_type(struct pseminfo, Z_WAITOK | Z_ZERO | Z_NOFAIL);
459 #if CONFIG_MACF
460 	mac_posixsem_label_init(new_pinfo);
461 #endif
462 
463 	/*
464 	 * Provisionally create the semaphore in the new_pinfo; we have to do
465 	 * this here to prevent locking later.  We use the value of kret to
466 	 * signal success or failure, which is why we set its default value
467 	 * to KERN_INVALID_ADDRESS, above.
468 	 */
469 
470 	fmode = (mode_t)FFLAGS(uap->oflag);
471 
472 	if ((fmode & O_CREAT)) {
473 		if ((value < 0) || (value > SEM_VALUE_MAX)) {
474 			error = EINVAL;
475 			goto bad;
476 		}
477 
478 		kret = semaphore_create(kernel_task, &new_pinfo->psem_semobject, SYNC_POLICY_FIFO, value);
479 
480 		if (kret != KERN_SUCCESS) {
481 			switch (kret) {
482 			case KERN_RESOURCE_SHORTAGE:
483 				error = ENOMEM;
484 				break;
485 			case KERN_PROTECTION_FAILURE:
486 				error = EACCES;
487 				break;
488 			default:
489 				error = EINVAL;
490 			}
491 			goto bad;
492 		}
493 	}
494 
495 	new_pnode = kalloc_type(struct psemnode, Z_WAITOK | Z_ZERO | Z_NOFAIL);
496 
497 	PSEM_SUBSYS_LOCK();
498 	error = psem_cache_search(&pinfo, &nd, &pcache);
499 
500 	if (error == PSEMCACHE_NEGATIVE) {
501 		error = EINVAL;
502 		goto bad_locked;
503 	}
504 
505 	if (error == PSEMCACHE_FOUND) {
506 		incache = 1;
507 	} else {
508 		incache = 0;
509 	}
510 
511 	cmode &=  ALLPERMS;
512 
513 	if (((fmode & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) && incache) {
514 		/* sem exists and opened O_EXCL */
515 #if notyet
516 		if (pinfo->psem_flags & PSEM_INDELETE) {
517 		}
518 #endif
519 		AUDIT_ARG(posix_ipc_perm, pinfo->psem_uid,
520 		    pinfo->psem_gid, pinfo->psem_mode);
521 		error = EEXIST;
522 		goto bad_locked;
523 	}
524 	if (((fmode & (O_CREAT | O_EXCL)) == O_CREAT) && incache) {
525 		/* As per POSIX, O_CREAT has no effect */
526 		fmode &= ~O_CREAT;
527 	}
528 
529 	if ((fmode & O_CREAT)) {
530 		/* create a new one (commit the allocation) */
531 		pinfo = new_pinfo;
532 		pinfo->psem_flags = PSEM_DEFINED | PSEM_INCREATE;
533 		pinfo->psem_usecount = 1;
534 		pinfo->psem_mode = cmode;
535 		pinfo->psem_uid = kauth_getuid();
536 		pinfo->psem_gid = kauth_getgid();
537 		bcopy(pnbuf, &pinfo->psem_name[0], PSEMNAMLEN);
538 		pinfo->psem_name[PSEMNAMLEN] = 0;
539 		pinfo->psem_flags &= ~PSEM_DEFINED;
540 		pinfo->psem_flags |= PSEM_ALLOCATED;
541 		pinfo->psem_creator_pid = proc_getpid(p);
542 		pinfo->psem_creator_uniqueid = proc_uniqueid(p);
543 
544 #if CONFIG_MACF
545 		error = mac_posixsem_check_create(kauth_cred_get(), nameptr);
546 		if (error) {
547 			goto bad_locked;
548 		}
549 		mac_posixsem_label_associate(kauth_cred_get(), pinfo, nameptr);
550 #endif
551 	} else {
552 		/* semaphore should exist as it is without  O_CREAT */
553 		if (!incache) {
554 			error = ENOENT;
555 			goto bad_locked;
556 		}
557 		if (pinfo->psem_flags & PSEM_INDELETE) {
558 			error = ENOENT;
559 			goto bad_locked;
560 		}
561 		AUDIT_ARG(posix_ipc_perm, pinfo->psem_uid,
562 		    pinfo->psem_gid, pinfo->psem_mode);
563 #if CONFIG_MACF
564 		error = mac_posixsem_check_open(kauth_cred_get(), pinfo);
565 		if (error) {
566 			goto bad_locked;
567 		}
568 #endif
569 		if ((error = psem_access(pinfo, fmode, kauth_cred_get()))) {
570 			goto bad_locked;
571 		}
572 	}
573 
574 	if (!incache) {
575 		/* if successful, this will consume the pcp */
576 		if ((error = psem_cache_add(pinfo, &nd, pcp))) {
577 			goto bad_locked;
578 		}
579 	}
580 	pinfo->psem_flags &= ~PSEM_INCREATE;
581 	pinfo->psem_usecount++;
582 	new_pnode->pinfo = pinfo;
583 	PSEM_SUBSYS_UNLOCK();
584 
585 	/*
586 	 * if incache, we did not use the new pcp or the new pcp or the
587 	 * new . and we must free them.
588 	 */
589 	if (incache) {
590 		kfree_type(struct psemcache, pcp);
591 		pcp = PSEMCACHE_NULL;
592 		if (new_pinfo != PSEMINFO_NULL) {
593 			/* return value ignored - we can't _not_ do this */
594 			(void)semaphore_destroy(kernel_task, new_pinfo->psem_semobject);
595 #if CONFIG_MACF
596 			mac_posixsem_label_destroy(new_pinfo);
597 #endif
598 			kfree_type(struct pseminfo, new_pinfo);
599 			new_pinfo = PSEMINFO_NULL;
600 		}
601 	}
602 
603 	proc_fdlock(p);
604 	fp->f_flag = fmode & FMASK;
605 	fp->f_ops = &psemops;
606 	fp_set_data(fp, new_pnode);
607 	procfdtbl_releasefd(p, indx, NULL);
608 	fp_drop(p, indx, fp, 1);
609 	proc_fdunlock(p);
610 
611 	*retval = CAST_USER_ADDR_T(indx);
612 	zfree(ZV_NAMEI, pnbuf);
613 	return 0;
614 
615 bad_locked:
616 	PSEM_SUBSYS_UNLOCK();
617 bad:
618 	kfree_type(struct psemcache, pcp);
619 
620 	kfree_type(struct psemnode, new_pnode);
621 
622 	if (fp != NULL) {
623 		fp_free(p, indx, fp);
624 	}
625 
626 	if (new_pinfo != PSEMINFO_NULL) {
627 		/*
628 		 * kret signals whether or not we successfully created a
629 		 * Mach semaphore for this semaphore; if so, we need to
630 		 * destroy it here.
631 		 */
632 		if (kret == KERN_SUCCESS) {
633 			/* return value ignored - we can't _not_ do this */
634 			(void)semaphore_destroy(kernel_task, new_pinfo->psem_semobject);
635 		}
636 #if CONFIG_MACF
637 		mac_posixsem_label_destroy(new_pinfo);
638 #endif
639 		kfree_type(struct pseminfo, new_pinfo);
640 	}
641 
642 	if (pnbuf != NULL) {
643 		zfree(ZV_NAMEI, pnbuf);
644 	}
645 	return error;
646 }
647 
648 /*
649  * XXX This code is repeated in several places
650  */
651 static int
psem_access(struct pseminfo * pinfo,mode_t mode,kauth_cred_t cred)652 psem_access(struct pseminfo *pinfo, mode_t mode, kauth_cred_t cred)
653 {
654 	mode_t mode_req = ((mode & FREAD) ? S_IRUSR : 0) |
655 	    ((mode & FWRITE) ? S_IWUSR : 0);
656 
657 	/* Otherwise, user id 0 always gets access. */
658 	if (!suser(cred, NULL)) {
659 		return 0;
660 	}
661 
662 	return posix_cred_access(cred, pinfo->psem_uid, pinfo->psem_gid, pinfo->psem_mode, mode_req);
663 }
664 
665 static int
psem_unlink_internal(struct pseminfo * pinfo,struct psemcache * pcache)666 psem_unlink_internal(struct pseminfo *pinfo, struct psemcache *pcache)
667 {
668 	PSEM_SUBSYS_ASSERT_HELD();
669 
670 	if (!pinfo || !pcache) {
671 		return EINVAL;
672 	}
673 
674 	if ((pinfo->psem_flags & (PSEM_DEFINED | PSEM_ALLOCATED)) == 0) {
675 		return EINVAL;
676 	}
677 
678 	if (pinfo->psem_flags & PSEM_INDELETE) {
679 		return 0;
680 	}
681 
682 	AUDIT_ARG(posix_ipc_perm, pinfo->psem_uid, pinfo->psem_gid,
683 	    pinfo->psem_mode);
684 
685 	pinfo->psem_flags |= PSEM_INDELETE;
686 	pinfo->psem_usecount--;
687 
688 	if (!pinfo->psem_usecount) {
689 		psem_delete(pinfo);
690 		kfree_type(struct pseminfo, pinfo);
691 	} else {
692 		pinfo->psem_flags |= PSEM_REMOVED;
693 	}
694 
695 	psem_cache_delete(pcache);
696 	kfree_type(struct psemcache, pcache);
697 	return 0;
698 }
699 
700 
701 int
sem_unlink(__unused proc_t p,struct sem_unlink_args * uap,__unused int32_t * retval)702 sem_unlink(__unused proc_t p, struct sem_unlink_args *uap, __unused int32_t *retval)
703 {
704 	size_t i;
705 	int error = 0;
706 	struct psemname nd;
707 	struct pseminfo *pinfo;
708 	char * nameptr;
709 	char * cp;
710 	char * pnbuf;
711 	size_t pathlen;
712 	struct psemcache *pcache = PSEMCACHE_NULL;
713 
714 	pinfo = PSEMINFO_NULL;
715 
716 	pnbuf = zalloc(ZV_NAMEI);
717 
718 	pathlen = MAXPATHLEN;
719 	error = copyinstr(uap->name, pnbuf, MAXPATHLEN, &pathlen);
720 	if (error) {
721 		goto bad;
722 	}
723 	AUDIT_ARG(text, pnbuf);
724 	if (pathlen > PSEMNAMLEN) {
725 		error = ENAMETOOLONG;
726 		goto bad;
727 	}
728 
729 	nameptr = pnbuf;
730 
731 #ifdef PSXSEM_NAME_RESTRICT
732 	if (*nameptr == '/') {
733 		while (*(nameptr++) == '/') {
734 			pathlen--;
735 			error = EINVAL;
736 			goto bad;
737 		}
738 	} else {
739 		error = EINVAL;
740 		goto bad;
741 	}
742 #endif /* PSXSEM_NAME_RESTRICT */
743 
744 	nd.psem_nameptr = nameptr;
745 	nd.psem_namelen = pathlen;
746 	nd.psem_hash = 0;
747 
748 	for (cp = nameptr, i = 1; *cp != 0 && i <= pathlen; i++, cp++) {
749 		nd.psem_hash += (unsigned char)*cp * i;
750 	}
751 
752 	PSEM_SUBSYS_LOCK();
753 	error = psem_cache_search(&pinfo, &nd, &pcache);
754 
755 	if (error != PSEMCACHE_FOUND) {
756 		PSEM_SUBSYS_UNLOCK();
757 		error = ENOENT;
758 		goto bad;
759 	}
760 
761 #if CONFIG_MACF
762 	error = mac_posixsem_check_unlink(kauth_cred_get(), pinfo, nameptr);
763 	if (error) {
764 		PSEM_SUBSYS_UNLOCK();
765 		goto bad;
766 	}
767 #endif
768 	if ((error = psem_access(pinfo, pinfo->psem_mode, kauth_cred_get()))) {
769 		PSEM_SUBSYS_UNLOCK();
770 		goto bad;
771 	}
772 
773 	error = psem_unlink_internal(pinfo, pcache);
774 	PSEM_SUBSYS_UNLOCK();
775 
776 bad:
777 	zfree(ZV_NAMEI, pnbuf);
778 	return error;
779 }
780 
781 int
sem_close(proc_t p,struct sem_close_args * uap,__unused int32_t * retval)782 sem_close(proc_t p, struct sem_close_args *uap, __unused int32_t *retval)
783 {
784 	int fd = CAST_DOWN_EXPLICIT(int, uap->sem);
785 	struct fileproc *fp;
786 
787 	AUDIT_ARG(fd, fd); /* XXX This seems wrong; uap->sem is a pointer */
788 
789 	proc_fdlock(p);
790 	if ((fp = fp_get_noref_locked(p, fd)) == NULL) {
791 		proc_fdunlock(p);
792 		return EBADF;
793 	}
794 	if (FILEGLOB_DTYPE(fp->fp_glob) != DTYPE_PSXSEM) {
795 		proc_fdunlock(p);
796 		return EBADF;
797 	}
798 	return fp_close_and_unlock(p, fd, fp, 0);
799 }
800 
801 int
sem_wait(proc_t p,struct sem_wait_args * uap,int32_t * retval)802 sem_wait(proc_t p, struct sem_wait_args *uap, int32_t *retval)
803 {
804 	__pthread_testcancel(1);
805 	return sem_wait_nocancel(p, (struct sem_wait_nocancel_args *)uap, retval);
806 }
807 
808 int
sem_wait_nocancel(proc_t p,struct sem_wait_nocancel_args * uap,__unused int32_t * retval)809 sem_wait_nocancel(proc_t p, struct sem_wait_nocancel_args *uap, __unused int32_t *retval)
810 {
811 	int fd = CAST_DOWN_EXPLICIT(int, uap->sem);
812 	struct fileproc *fp;
813 	struct pseminfo * pinfo;
814 	struct psemnode * pnode;
815 	kern_return_t kret;
816 	int error;
817 
818 	error = fp_get_ftype(p, fd, DTYPE_PSXSEM, EBADF, &fp);
819 	if (error) {
820 		return error;
821 	}
822 	pnode = (struct psemnode *)fp_get_data(fp);
823 
824 	PSEM_SUBSYS_LOCK();
825 	if ((pinfo = pnode->pinfo) == PSEMINFO_NULL) {
826 		PSEM_SUBSYS_UNLOCK();
827 		error = EINVAL;
828 		goto out;
829 	}
830 	if ((pinfo->psem_flags & (PSEM_DEFINED | PSEM_ALLOCATED))
831 	    != PSEM_ALLOCATED) {
832 		PSEM_SUBSYS_UNLOCK();
833 		error = EINVAL;
834 		goto out;
835 	}
836 #if CONFIG_MACF
837 	error = mac_posixsem_check_wait(kauth_cred_get(), pinfo);
838 	if (error) {
839 		PSEM_SUBSYS_UNLOCK();
840 		goto out;
841 	}
842 #endif
843 	PSEM_SUBSYS_UNLOCK();
844 	kret = semaphore_wait(pinfo->psem_semobject);
845 	switch (kret) {
846 	case KERN_INVALID_ADDRESS:
847 	case KERN_PROTECTION_FAILURE:
848 		error = EACCES;
849 		break;
850 	case KERN_ABORTED:
851 	case KERN_OPERATION_TIMED_OUT:
852 		error = EINTR;
853 		break;
854 	case KERN_SUCCESS:
855 		error = 0;
856 		break;
857 	default:
858 		error = EINVAL;
859 		break;
860 	}
861 out:
862 	fp_drop(p, fd, fp, 0);
863 	return error;
864 }
865 
866 int
sem_trywait(proc_t p,struct sem_trywait_args * uap,__unused int32_t * retval)867 sem_trywait(proc_t p, struct sem_trywait_args *uap, __unused int32_t *retval)
868 {
869 	int fd = CAST_DOWN_EXPLICIT(int, uap->sem);
870 	struct fileproc *fp;
871 	struct pseminfo * pinfo;
872 	struct psemnode * pnode;
873 	kern_return_t kret;
874 	mach_timespec_t wait_time;
875 	int error;
876 
877 	error = fp_get_ftype(p, fd, DTYPE_PSXSEM, EBADF, &fp);
878 	if (error) {
879 		return error;
880 	}
881 	pnode = (struct psemnode *)fp_get_data(fp);
882 
883 	PSEM_SUBSYS_LOCK();
884 	if ((pinfo = pnode->pinfo) == PSEMINFO_NULL) {
885 		PSEM_SUBSYS_UNLOCK();
886 		error = EINVAL;
887 		goto out;
888 	}
889 	if ((pinfo->psem_flags & (PSEM_DEFINED | PSEM_ALLOCATED))
890 	    != PSEM_ALLOCATED) {
891 		PSEM_SUBSYS_UNLOCK();
892 		error = EINVAL;
893 		goto out;
894 	}
895 #if CONFIG_MACF
896 	error = mac_posixsem_check_wait(kauth_cred_get(), pinfo);
897 	if (error) {
898 		PSEM_SUBSYS_UNLOCK();
899 		goto out;
900 	}
901 #endif
902 	PSEM_SUBSYS_UNLOCK();
903 	wait_time.tv_sec = 0;
904 	wait_time.tv_nsec = 0;
905 
906 	kret = semaphore_timedwait(pinfo->psem_semobject, MACH_TIMESPEC_ZERO);
907 	switch (kret) {
908 	case KERN_INVALID_ADDRESS:
909 	case KERN_PROTECTION_FAILURE:
910 		error = EINVAL;
911 		break;
912 	case KERN_ABORTED:
913 		error = EINTR;
914 		break;
915 	case KERN_OPERATION_TIMED_OUT:
916 		error = EAGAIN;
917 		break;
918 	case KERN_SUCCESS:
919 		error = 0;
920 		break;
921 	default:
922 		error = EINVAL;
923 		break;
924 	}
925 out:
926 	fp_drop(p, fd, fp, 0);
927 	return error;
928 }
929 
930 int
sem_post(proc_t p,struct sem_post_args * uap,__unused int32_t * retval)931 sem_post(proc_t p, struct sem_post_args *uap, __unused int32_t *retval)
932 {
933 	int fd = CAST_DOWN_EXPLICIT(int, uap->sem);
934 	struct fileproc *fp;
935 	struct pseminfo * pinfo;
936 	struct psemnode * pnode;
937 	kern_return_t kret;
938 	int error;
939 
940 	error = fp_get_ftype(p, fd, DTYPE_PSXSEM, EBADF, &fp);
941 	if (error) {
942 		return error;
943 	}
944 	pnode = (struct psemnode *)fp_get_data(fp);
945 
946 	PSEM_SUBSYS_LOCK();
947 	if ((pinfo = pnode->pinfo) == PSEMINFO_NULL) {
948 		PSEM_SUBSYS_UNLOCK();
949 		error = EINVAL;
950 		goto out;
951 	}
952 	if ((pinfo->psem_flags & (PSEM_DEFINED | PSEM_ALLOCATED))
953 	    != PSEM_ALLOCATED) {
954 		PSEM_SUBSYS_UNLOCK();
955 		error = EINVAL;
956 		goto out;
957 	}
958 #if CONFIG_MACF
959 	error = mac_posixsem_check_post(kauth_cred_get(), pinfo);
960 	if (error) {
961 		PSEM_SUBSYS_UNLOCK();
962 		goto out;
963 	}
964 #endif
965 	PSEM_SUBSYS_UNLOCK();
966 	kret = semaphore_signal(pinfo->psem_semobject);
967 	switch (kret) {
968 	case KERN_INVALID_ADDRESS:
969 	case KERN_PROTECTION_FAILURE:
970 		error = EINVAL;
971 		break;
972 	case KERN_ABORTED:
973 	case KERN_OPERATION_TIMED_OUT:
974 		error = EINTR;
975 		break;
976 	case KERN_SUCCESS:
977 		error = 0;
978 		break;
979 	default:
980 		error = EINVAL;
981 		break;
982 	}
983 out:
984 	fp_drop(p, fd, fp, 0);
985 	return error;
986 }
987 
988 static int
psem_close(struct psemnode * pnode)989 psem_close(struct psemnode *pnode)
990 {
991 	int error = 0;
992 	struct pseminfo *pinfo;
993 
994 	PSEM_SUBSYS_LOCK();
995 	if ((pinfo = pnode->pinfo) == PSEMINFO_NULL) {
996 		PSEM_SUBSYS_UNLOCK();
997 		return EINVAL;
998 	}
999 
1000 	if ((pinfo->psem_flags & PSEM_ALLOCATED) != PSEM_ALLOCATED) {
1001 		PSEM_SUBSYS_UNLOCK();
1002 		return EINVAL;
1003 	}
1004 #if DIAGNOSTIC
1005 	if (!pinfo->psem_usecount) {
1006 		kprintf("negative usecount in psem_close\n");
1007 	}
1008 #endif /* DIAGNOSTIC */
1009 	pinfo->psem_usecount--;
1010 
1011 	if ((pinfo->psem_flags & PSEM_REMOVED) && !pinfo->psem_usecount) {
1012 		PSEM_SUBSYS_UNLOCK();
1013 		/* lock dropped as only semaphore is destroyed here */
1014 		error = psem_delete(pinfo);
1015 		kfree_type(struct pseminfo, pinfo);
1016 	} else {
1017 		PSEM_SUBSYS_UNLOCK();
1018 	}
1019 	/* subsystem lock is dropped when we get here */
1020 	kfree_type(struct psemnode, pnode);
1021 	return error;
1022 }
1023 
1024 static int
psem_closefile(struct fileglob * fg,__unused vfs_context_t ctx)1025 psem_closefile(struct fileglob *fg, __unused vfs_context_t ctx)
1026 {
1027 	/*
1028 	 * Not locked as psem_close is called only from here and is locked
1029 	 * properly
1030 	 */
1031 	return psem_close((struct psemnode *)fg_get_data(fg));
1032 }
1033 
1034 static int
psem_delete(struct pseminfo * pinfo)1035 psem_delete(struct pseminfo * pinfo)
1036 {
1037 	kern_return_t kret;
1038 
1039 	kret = semaphore_destroy(kernel_task, pinfo->psem_semobject);
1040 #if CONFIG_MACF
1041 	mac_posixsem_label_destroy(pinfo);
1042 #endif
1043 
1044 	switch (kret) {
1045 	case KERN_INVALID_ADDRESS:
1046 	case KERN_PROTECTION_FAILURE:
1047 		return EINVAL;
1048 	case KERN_ABORTED:
1049 	case KERN_OPERATION_TIMED_OUT:
1050 		return EINTR;
1051 	case KERN_SUCCESS:
1052 		return 0;
1053 	default:
1054 		return EINVAL;
1055 	}
1056 }
1057 
1058 int
fill_pseminfo(struct psemnode * pnode,struct psem_info * info)1059 fill_pseminfo(struct psemnode *pnode, struct psem_info * info)
1060 {
1061 	struct pseminfo *pinfo;
1062 	struct vinfo_stat  *sb;
1063 
1064 	PSEM_SUBSYS_LOCK();
1065 	if ((pinfo = pnode->pinfo) == PSEMINFO_NULL) {
1066 		PSEM_SUBSYS_UNLOCK();
1067 		return EINVAL;
1068 	}
1069 
1070 #if 0
1071 	if ((pinfo->psem_flags & PSEM_ALLOCATED) != PSEM_ALLOCATED) {
1072 		PSEM_SUBSYS_UNLOCK();
1073 		return EINVAL;
1074 	}
1075 #endif
1076 
1077 	sb = &info->psem_stat;
1078 	bzero(sb, sizeof(struct vinfo_stat));
1079 
1080 	sb->vst_mode = pinfo->psem_mode;
1081 	sb->vst_uid = pinfo->psem_uid;
1082 	sb->vst_gid = pinfo->psem_gid;
1083 	sb->vst_size = pinfo->psem_usecount;
1084 	bcopy(&pinfo->psem_name[0], &info->psem_name[0], PSEMNAMLEN + 1);
1085 
1086 	PSEM_SUBSYS_UNLOCK();
1087 	return 0;
1088 }
1089 
1090 #if CONFIG_MACF
1091 void
psem_label_associate(struct fileproc * fp,struct vnode * vp,vfs_context_t ctx)1092 psem_label_associate(struct fileproc *fp, struct vnode *vp, vfs_context_t ctx)
1093 {
1094 	struct psemnode *pnode;
1095 	struct pseminfo *psem;
1096 
1097 	PSEM_SUBSYS_LOCK();
1098 	pnode = (struct psemnode *)fp_get_data(fp);
1099 	if (pnode != NULL) {
1100 		psem = pnode->pinfo;
1101 		if (psem != NULL) {
1102 			mac_posixsem_vnode_label_associate(
1103 				vfs_context_ucred(ctx), psem,
1104 				mac_posixsem_label(psem),
1105 				vp, mac_vnode_label(vp));
1106 		}
1107 	}
1108 	PSEM_SUBSYS_UNLOCK();
1109 }
1110 #endif
1111