xref: /titanic_50/usr/src/uts/common/fs/sockfs/socksubr.c (revision bdfc6d18da790deeec2e0eb09c625902defe2498)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <sys/types.h>
30 #include <sys/t_lock.h>
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/buf.h>
34 #include <sys/conf.h>
35 #include <sys/cred.h>
36 #include <sys/kmem.h>
37 #include <sys/sysmacros.h>
38 #include <sys/vfs.h>
39 #include <sys/vnode.h>
40 #include <sys/debug.h>
41 #include <sys/errno.h>
42 #include <sys/time.h>
43 #include <sys/file.h>
44 #include <sys/open.h>
45 #include <sys/user.h>
46 #include <sys/termios.h>
47 #include <sys/stream.h>
48 #include <sys/strsubr.h>
49 #include <sys/strsun.h>
50 #include <sys/esunddi.h>
51 #include <sys/flock.h>
52 #include <sys/modctl.h>
53 #include <sys/cmn_err.h>
54 #include <sys/mkdev.h>
55 #include <sys/pathname.h>
56 #include <sys/ddi.h>
57 #include <sys/stat.h>
58 #include <sys/fs/snode.h>
59 #include <sys/fs/dv_node.h>
60 #include <sys/zone.h>
61 
62 #include <sys/socket.h>
63 #include <sys/socketvar.h>
64 #include <netinet/in.h>
65 #include <sys/un.h>
66 
67 #include <sys/ucred.h>
68 
69 #include <sys/tiuser.h>
70 #define	_SUN_TPI_VERSION	2
71 #include <sys/tihdr.h>
72 
73 #include <c2/audit.h>
74 
75 #include <fs/sockfs/nl7c.h>
76 
77 /*
78  * Macros that operate on struct cmsghdr.
79  * The CMSG_VALID macro does not assume that the last option buffer is padded.
80  */
81 #define	CMSG_CONTENT(cmsg)	(&((cmsg)[1]))
82 #define	CMSG_CONTENTLEN(cmsg)	((cmsg)->cmsg_len - sizeof (struct cmsghdr))
83 #define	CMSG_VALID(cmsg, start, end)					\
84 	(ISALIGNED_cmsghdr(cmsg) &&					\
85 	((uintptr_t)(cmsg) >= (uintptr_t)(start)) &&			\
86 	((uintptr_t)(cmsg) < (uintptr_t)(end)) &&			\
87 	((ssize_t)(cmsg)->cmsg_len >= sizeof (struct cmsghdr)) &&	\
88 	((uintptr_t)(cmsg) + (cmsg)->cmsg_len <= (uintptr_t)(end)))
89 #define	SO_LOCK_WAKEUP_TIME	3000	/* Wakeup time in milliseconds */
90 
91 static struct kmem_cache *socktpi_cache, *socktpi_unix_cache;
92 
93 dev_t sockdev;	/* For fsid in getattr */
94 
95 struct sockparams *sphead;
96 krwlock_t splist_lock;
97 
98 struct socklist socklist;
99 
100 static int sockfs_update(kstat_t *, int);
101 static int sockfs_snapshot(kstat_t *, void *, int);
102 
103 extern void sendfile_init();
104 
105 extern void nl7c_init(void);
106 
107 #define	ADRSTRLEN (2 * sizeof (void *) + 1)
108 /*
109  * kernel structure for passing the sockinfo data back up to the user.
110  * the strings array allows us to convert AF_UNIX addresses into strings
111  * with a common method regardless of which n-bit kernel we're running.
112  */
113 struct k_sockinfo {
114 	struct sockinfo	ks_si;
115 	char		ks_straddr[3][ADRSTRLEN];
116 };
117 
118 /*
119  * Translate from a device pathname (e.g. "/dev/tcp") to a vnode.
120  * Returns with the vnode held.
121  */
122 static int
123 sogetvp(char *devpath, vnode_t **vpp, int uioflag)
124 {
125 	struct snode *csp;
126 	vnode_t *vp, *dvp;
127 	major_t maj;
128 	int error;
129 
130 	ASSERT(uioflag == UIO_SYSSPACE || uioflag == UIO_USERSPACE);
131 	/*
132 	 * Lookup the underlying filesystem vnode.
133 	 */
134 	error = lookupname(devpath, uioflag, FOLLOW, NULLVPP, &vp);
135 	if (error)
136 		return (error);
137 
138 	/* Check that it is the correct vnode */
139 	if (vp->v_type != VCHR) {
140 		VN_RELE(vp);
141 		return (ENOTSOCK);
142 	}
143 
144 	/*
145 	 * If devpath went through devfs, the device should already
146 	 * be configured. If devpath is a mknod file, however, we
147 	 * need to make sure the device is properly configured.
148 	 * To do this, we do something similar to spec_open()
149 	 * except that we resolve to the minor/leaf level since
150 	 * we need to return a vnode.
151 	 */
152 	csp = VTOS(VTOS(vp)->s_commonvp);
153 	if (!(csp->s_flag & SDIPSET)) {
154 		char *pathname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
155 		error = ddi_dev_pathname(vp->v_rdev, S_IFCHR, pathname);
156 		if (error == 0)
157 			error = devfs_lookupname(pathname, NULLVPP, &dvp);
158 		VN_RELE(vp);
159 		kmem_free(pathname, MAXPATHLEN);
160 		if (error != 0)
161 			return (ENXIO);
162 		vp = dvp;	/* use the devfs vp */
163 	}
164 
165 	/* device is configured at this point */
166 	maj = getmajor(vp->v_rdev);
167 	if (!STREAMSTAB(maj)) {
168 		VN_RELE(vp);
169 		return (ENOSTR);
170 	}
171 
172 	*vpp = vp;
173 	return (0);
174 }
175 
176 /*
177  * Add or delete (latter if devpath is NULL) an enter to the sockparams
178  * table. If devpathlen is zero the devpath with not be kmem_freed. Otherwise
179  * this routine assumes that the caller has kmem_alloced devpath/devpathlen
180  * for this routine to consume.
181  * The zero devpathlen could be used if the kernel wants to create entries
182  * itself by calling sockconfig(1,2,3, "/dev/tcp", 0);
183  */
184 int
185 soconfig(int domain, int type, int protocol,
186     char *devpath, int devpathlen)
187 {
188 	struct sockparams **spp;
189 	struct sockparams *sp;
190 	int error = 0;
191 
192 	dprint(0, ("soconfig(%d,%d,%d,%s,%d)\n",
193 		domain, type, protocol, devpath, devpathlen));
194 
195 	/*
196 	 * Look for an existing match.
197 	 */
198 	rw_enter(&splist_lock, RW_WRITER);
199 	for (spp = &sphead; (sp = *spp) != NULL; spp = &sp->sp_next) {
200 		if (sp->sp_domain == domain &&
201 		    sp->sp_type == type &&
202 		    sp->sp_protocol == protocol) {
203 			break;
204 		}
205 	}
206 	if (devpath == NULL) {
207 		ASSERT(devpathlen == 0);
208 
209 		/* Delete existing entry */
210 		if (sp == NULL) {
211 			error = ENXIO;
212 			goto done;
213 		}
214 		/* Unlink and free existing entry */
215 		*spp = sp->sp_next;
216 		ASSERT(sp->sp_vnode);
217 		VN_RELE(sp->sp_vnode);
218 		if (sp->sp_devpathlen != 0)
219 			kmem_free(sp->sp_devpath, sp->sp_devpathlen);
220 		kmem_free(sp, sizeof (*sp));
221 	} else {
222 		vnode_t *vp;
223 
224 		/* Add new entry */
225 		if (sp != NULL) {
226 			error = EEXIST;
227 			goto done;
228 		}
229 
230 		error = sogetvp(devpath, &vp, UIO_SYSSPACE);
231 		if (error) {
232 			dprint(0, ("soconfig: vp %s failed with %d\n",
233 				devpath, error));
234 			goto done;
235 		}
236 
237 		dprint(0, ("soconfig: %s => vp %p, dev 0x%lx\n",
238 		    devpath, vp, vp->v_rdev));
239 
240 		sp = kmem_alloc(sizeof (*sp), KM_SLEEP);
241 		sp->sp_domain = domain;
242 		sp->sp_type = type;
243 		sp->sp_protocol = protocol;
244 		sp->sp_devpath = devpath;
245 		sp->sp_devpathlen = devpathlen;
246 		sp->sp_vnode = vp;
247 		sp->sp_next = NULL;
248 		*spp = sp;
249 	}
250 done:
251 	rw_exit(&splist_lock);
252 	if (error) {
253 		if (devpath != NULL)
254 			kmem_free(devpath, devpathlen);
255 #ifdef SOCK_DEBUG
256 		eprintline(error);
257 #endif /* SOCK_DEBUG */
258 	}
259 	return (error);
260 }
261 
262 /*
263  * Lookup an entry in the sockparams list based on the triple.
264  * If no entry is found and devpath is not NULL translate devpath to a
265  * vnode. Note that devpath is a pointer to a user address!
266  * Returns with the vnode held.
267  *
268  * When this routine uses devpath it does not create an entry in the sockparams
269  * list since this routine can run on behalf of any user and one user
270  * should not be able to effect the transport used by another user.
271  *
272  * In order to return the correct error this routine has to do wildcard scans
273  * of the list. The errors are (in decreasing precedence):
274  *	EAFNOSUPPORT - address family not in list
275  *	EPROTONOSUPPORT - address family supported but not protocol.
276  *	EPROTOTYPE - address family and protocol supported but not socket type.
277  */
278 vnode_t *
279 solookup(int domain, int type, int protocol, char *devpath, int *errorp)
280 {
281 	struct sockparams *sp;
282 	int error;
283 	vnode_t *vp;
284 
285 	rw_enter(&splist_lock, RW_READER);
286 	for (sp = sphead; sp != NULL; sp = sp->sp_next) {
287 		if (sp->sp_domain == domain &&
288 		    sp->sp_type == type &&
289 		    sp->sp_protocol == protocol) {
290 			break;
291 		}
292 	}
293 	if (sp == NULL) {
294 		dprint(0, ("solookup(%d,%d,%d) not found\n",
295 			domain, type, protocol));
296 		if (devpath == NULL) {
297 			/* Determine correct error code */
298 			int found = 0;
299 
300 			for (sp = sphead; sp != NULL; sp = sp->sp_next) {
301 				if (sp->sp_domain == domain && found < 1)
302 					found = 1;
303 				if (sp->sp_domain == domain &&
304 				    sp->sp_protocol == protocol && found < 2)
305 					found = 2;
306 			}
307 			rw_exit(&splist_lock);
308 			switch (found) {
309 			case 0:
310 				*errorp = EAFNOSUPPORT;
311 				break;
312 			case 1:
313 				*errorp = EPROTONOSUPPORT;
314 				break;
315 			case 2:
316 				*errorp = EPROTOTYPE;
317 				break;
318 			}
319 			return (NULL);
320 		}
321 		rw_exit(&splist_lock);
322 
323 		/*
324 		 * Return vp based on devpath.
325 		 * Do not enter into table to avoid random users
326 		 * modifying the sockparams list.
327 		 */
328 		error = sogetvp(devpath, &vp, UIO_USERSPACE);
329 		if (error) {
330 			dprint(0, ("solookup: vp %p failed with %d\n",
331 				devpath, error));
332 			*errorp = EPROTONOSUPPORT;
333 			return (NULL);
334 		}
335 		dprint(0, ("solookup: %p => vp %p, dev 0x%lx\n",
336 		    devpath, vp, vp->v_rdev));
337 
338 		return (vp);
339 	}
340 	dprint(0, ("solookup(%d,%d,%d) vp %p devpath %s\n",
341 		domain, type, protocol, sp->sp_vnode, sp->sp_devpath));
342 
343 	vp = sp->sp_vnode;
344 	VN_HOLD(vp);
345 	rw_exit(&splist_lock);
346 	return (vp);
347 }
348 
349 /*
350  * Return a socket vnode.
351  *
352  * Assumes that the caller is "passing" an VN_HOLD for accessvp i.e.
353  * when the socket is freed a VN_RELE will take place.
354  *
355  * Note that sockets assume that the driver will clone (either itself
356  * or by using the clone driver) i.e. a socket() call will always
357  * result in a new vnode being created.
358  */
359 struct vnode *
360 makesockvp(struct vnode *accessvp, int domain, int type, int protocol)
361 {
362 	kmem_cache_t *cp;
363 	struct sonode *so;
364 	struct vnode *vp;
365 	time_t now;
366 	dev_t dev;
367 
368 	cp = (domain == AF_UNIX) ? socktpi_unix_cache : socktpi_cache;
369 	so = kmem_cache_alloc(cp, KM_SLEEP);
370 	so->so_cache = cp;
371 	so->so_obj = so;
372 	vp = SOTOV(so);
373 	now = gethrestime_sec();
374 
375 	so->so_flag	= 0;
376 	ASSERT(so->so_accessvp == NULL);
377 	so->so_accessvp	= accessvp;
378 	dev = accessvp->v_rdev;
379 
380 	/*
381 	 * Record in so_flag that it is a clone.
382 	 */
383 	if (getmajor(dev) == clone_major) {
384 		so->so_flag |= SOCLONE;
385 	}
386 	so->so_dev = dev;
387 
388 	so->so_state	= 0;
389 	so->so_mode	= 0;
390 
391 	so->so_fsid	= sockdev;
392 	so->so_atime	= now;
393 	so->so_mtime	= now;
394 	so->so_ctime	= now;		/* Never modified */
395 	so->so_count	= 0;
396 
397 	so->so_family	= (short)domain;
398 	so->so_type	= (short)type;
399 	so->so_protocol	= (short)protocol;
400 	so->so_pushcnt	= 0;
401 
402 	so->so_options	= 0;
403 	so->so_linger.l_onoff	= 0;
404 	so->so_linger.l_linger = 0;
405 	so->so_sndbuf	= 0;
406 	so->so_rcvbuf	= 0;
407 	so->so_sndlowat	= 0;
408 	so->so_rcvlowat	= 0;
409 #ifdef notyet
410 	so->so_sndtimeo	= 0;
411 	so->so_rcvtimeo	= 0;
412 #endif /* notyet */
413 	so->so_error	= 0;
414 	so->so_delayed_error = 0;
415 
416 	ASSERT(so->so_oobmsg == NULL);
417 	so->so_oobcnt	= 0;
418 	so->so_oobsigcnt = 0;
419 	so->so_pgrp	= 0;
420 	so->so_provinfo = NULL;
421 
422 	ASSERT(so->so_laddr_sa == NULL && so->so_faddr_sa == NULL);
423 	so->so_laddr_len = so->so_faddr_len = 0;
424 	so->so_laddr_maxlen = so->so_faddr_maxlen = 0;
425 	so->so_eaddr_mp = NULL;
426 	so->so_priv = NULL;
427 
428 	so->so_peercred = NULL;
429 
430 	ASSERT(so->so_ack_mp == NULL);
431 	ASSERT(so->so_conn_ind_head == NULL);
432 	ASSERT(so->so_conn_ind_tail == NULL);
433 	ASSERT(so->so_ux_bound_vp == NULL);
434 	ASSERT(so->so_unbind_mp == NULL);
435 
436 	vn_reinit(vp);
437 	vp->v_vfsp	= rootvfs;
438 	vp->v_type	= VSOCK;
439 	vp->v_rdev	= so->so_dev;
440 	vn_exists(vp);
441 
442 	return (vp);
443 }
444 
445 void
446 sockfree(struct sonode *so)
447 {
448 	mblk_t *mp;
449 	vnode_t *vp;
450 
451 	ASSERT(so->so_count == 0);
452 	ASSERT(so->so_accessvp);
453 	ASSERT(so->so_discon_ind_mp == NULL);
454 
455 	vp = so->so_accessvp;
456 	VN_RELE(vp);
457 
458 	/*
459 	 * Protect so->so_[lf]addr_sa so that sockfs_snapshot() can safely
460 	 * indirect them.  It also uses so_accessvp as a validity test.
461 	 */
462 	mutex_enter(&so->so_lock);
463 
464 	so->so_accessvp = NULL;
465 
466 	if (so->so_laddr_sa) {
467 		ASSERT((caddr_t)so->so_faddr_sa ==
468 		    (caddr_t)so->so_laddr_sa + so->so_laddr_maxlen);
469 		ASSERT(so->so_faddr_maxlen == so->so_laddr_maxlen);
470 		so->so_state &= ~(SS_LADDR_VALID | SS_FADDR_VALID);
471 		kmem_free(so->so_laddr_sa, so->so_laddr_maxlen * 2);
472 		so->so_laddr_sa = NULL;
473 		so->so_laddr_len = so->so_laddr_maxlen = 0;
474 		so->so_faddr_sa = NULL;
475 		so->so_faddr_len = so->so_faddr_maxlen = 0;
476 	}
477 
478 	mutex_exit(&so->so_lock);
479 
480 	if ((mp = so->so_eaddr_mp) != NULL) {
481 		freemsg(mp);
482 		so->so_eaddr_mp = NULL;
483 		so->so_delayed_error = 0;
484 	}
485 	if ((mp = so->so_ack_mp) != NULL) {
486 		freemsg(mp);
487 		so->so_ack_mp = NULL;
488 	}
489 	if ((mp = so->so_conn_ind_head) != NULL) {
490 		mblk_t *mp1;
491 
492 		while (mp) {
493 			mp1 = mp->b_next;
494 			mp->b_next = NULL;
495 			freemsg(mp);
496 			mp = mp1;
497 		}
498 		so->so_conn_ind_head = so->so_conn_ind_tail = NULL;
499 		so->so_state &= ~SS_HASCONNIND;
500 	}
501 #ifdef DEBUG
502 	mutex_enter(&so->so_lock);
503 	ASSERT(so_verify_oobstate(so));
504 	mutex_exit(&so->so_lock);
505 #endif /* DEBUG */
506 	if ((mp = so->so_oobmsg) != NULL) {
507 		freemsg(mp);
508 		so->so_oobmsg = NULL;
509 		so->so_state &= ~(SS_OOBPEND|SS_HAVEOOBDATA|SS_HADOOBDATA);
510 	}
511 
512 	if ((mp = so->so_nl7c_rcv_mp) != NULL) {
513 		so->so_nl7c_rcv_mp = NULL;
514 		freemsg(mp);
515 	}
516 	so->so_nl7c_rcv_rval = 0;
517 	if (so->so_nl7c_uri != NULL) {
518 		nl7c_urifree(so);
519 	}
520 	so->so_nl7c_flags = 0;
521 
522 	ASSERT(so->so_ux_bound_vp == NULL);
523 	if ((mp = so->so_unbind_mp) != NULL) {
524 		freemsg(mp);
525 		so->so_unbind_mp = NULL;
526 	}
527 	vn_invalid(SOTOV(so));
528 
529 	if (so->so_peercred != NULL)
530 		crfree(so->so_peercred);
531 
532 	kmem_cache_free(so->so_cache, so->so_obj);
533 }
534 
535 /*
536  * Update the accessed, updated, or changed times in an sonode
537  * with the current time.
538  *
539  * Note that both SunOS 4.X and 4.4BSD sockets do not present reasonable
540  * attributes in a fstat call. (They return the current time and 0 for
541  * all timestamps, respectively.) We maintain the current timestamps
542  * here primarily so that should sockmod be popped the resulting
543  * file descriptor will behave like a stream w.r.t. the timestamps.
544  */
545 void
546 so_update_attrs(struct sonode *so, int flag)
547 {
548 	time_t now = gethrestime_sec();
549 
550 	mutex_enter(&so->so_lock);
551 	so->so_flag |= flag;
552 	if (flag & SOACC)
553 		so->so_atime = now;
554 	if (flag & SOMOD)
555 		so->so_mtime = now;
556 	mutex_exit(&so->so_lock);
557 }
558 
559 /*ARGSUSED*/
560 static int
561 socktpi_constructor(void *buf, void *cdrarg, int kmflags)
562 {
563 	struct sonode *so = buf;
564 	struct vnode *vp;
565 
566 	so->so_nl7c_flags	= 0;
567 	so->so_nl7c_uri		= NULL;
568 	so->so_nl7c_rcv_mp	= NULL;
569 
570 	so->so_oobmsg		= NULL;
571 	so->so_ack_mp		= NULL;
572 	so->so_conn_ind_head	= NULL;
573 	so->so_conn_ind_tail	= NULL;
574 	so->so_discon_ind_mp	= NULL;
575 	so->so_ux_bound_vp	= NULL;
576 	so->so_unbind_mp	= NULL;
577 	so->so_accessvp		= NULL;
578 	so->so_laddr_sa		= NULL;
579 	so->so_faddr_sa		= NULL;
580 	so->so_ops		= &sotpi_sonodeops;
581 
582 	vp = vn_alloc(KM_SLEEP);
583 	so->so_vnode = vp;
584 
585 	vn_setops(vp, socktpi_vnodeops);
586 	vp->v_data = (caddr_t)so;
587 
588 	mutex_init(&so->so_lock, NULL, MUTEX_DEFAULT, NULL);
589 	mutex_init(&so->so_plumb_lock, NULL, MUTEX_DEFAULT, NULL);
590 	cv_init(&so->so_state_cv, NULL, CV_DEFAULT, NULL);
591 	cv_init(&so->so_ack_cv, NULL, CV_DEFAULT, NULL);
592 	cv_init(&so->so_connind_cv, NULL, CV_DEFAULT, NULL);
593 	cv_init(&so->so_want_cv, NULL, CV_DEFAULT, NULL);
594 
595 	return (0);
596 }
597 
598 /*ARGSUSED1*/
599 static void
600 socktpi_destructor(void *buf, void *cdrarg)
601 {
602 	struct sonode *so = buf;
603 	struct vnode *vp = SOTOV(so);
604 
605 	ASSERT(so->so_nl7c_flags == 0);
606 	ASSERT(so->so_nl7c_uri == NULL);
607 	ASSERT(so->so_nl7c_rcv_mp == NULL);
608 
609 	ASSERT(so->so_oobmsg == NULL);
610 	ASSERT(so->so_ack_mp == NULL);
611 	ASSERT(so->so_conn_ind_head == NULL);
612 	ASSERT(so->so_conn_ind_tail == NULL);
613 	ASSERT(so->so_discon_ind_mp == NULL);
614 	ASSERT(so->so_ux_bound_vp == NULL);
615 	ASSERT(so->so_unbind_mp == NULL);
616 	ASSERT(so->so_ops == &sotpi_sonodeops);
617 
618 	ASSERT(vn_matchops(vp, socktpi_vnodeops));
619 	ASSERT(vp->v_data == (caddr_t)so);
620 
621 	vn_free(vp);
622 
623 	mutex_destroy(&so->so_lock);
624 	mutex_destroy(&so->so_plumb_lock);
625 	cv_destroy(&so->so_state_cv);
626 	cv_destroy(&so->so_ack_cv);
627 	cv_destroy(&so->so_connind_cv);
628 	cv_destroy(&so->so_want_cv);
629 }
630 
631 static int
632 socktpi_unix_constructor(void *buf, void *cdrarg, int kmflags)
633 {
634 	int retval;
635 
636 	if ((retval = socktpi_constructor(buf, cdrarg, kmflags)) == 0) {
637 		struct sonode *so = (struct sonode *)buf;
638 
639 		mutex_enter(&socklist.sl_lock);
640 
641 		so->so_next = socklist.sl_list;
642 		so->so_prev = NULL;
643 		if (so->so_next != NULL)
644 			so->so_next->so_prev = so;
645 		socklist.sl_list = so;
646 
647 		mutex_exit(&socklist.sl_lock);
648 
649 	}
650 	return (retval);
651 }
652 
653 static void
654 socktpi_unix_destructor(void *buf, void *cdrarg)
655 {
656 	struct sonode	*so	= (struct sonode *)buf;
657 
658 	mutex_enter(&socklist.sl_lock);
659 
660 	if (so->so_next != NULL)
661 		so->so_next->so_prev = so->so_prev;
662 	if (so->so_prev != NULL)
663 		so->so_prev->so_next = so->so_next;
664 	else
665 		socklist.sl_list = so->so_next;
666 
667 	mutex_exit(&socklist.sl_lock);
668 
669 	socktpi_destructor(buf, cdrarg);
670 }
671 
672 /*
673  * Init function called when sockfs is loaded.
674  */
675 int
676 sockinit(int fstype, char *name)
677 {
678 	static const fs_operation_def_t sock_vfsops_template[] = {
679 		NULL, NULL
680 	};
681 	int error;
682 	major_t dev;
683 	char *err_str;
684 
685 	error = vfs_setfsops(fstype, sock_vfsops_template, NULL);
686 	if (error != 0) {
687 		cmn_err(CE_WARN, "sockinit: bad vfs ops template");
688 		return (error);
689 	}
690 
691 	error = vn_make_ops(name, socktpi_vnodeops_template, &socktpi_vnodeops);
692 	if (error != 0) {
693 		err_str = "sockinit: bad sock vnode ops template";
694 		/* vn_make_ops() does not reset socktpi_vnodeops on failure. */
695 		socktpi_vnodeops = NULL;
696 		goto failure;
697 	}
698 
699 	error = vn_make_ops("nca", socknca_vnodeops_template,
700 	    &socknca_vnodeops);
701 	if (error != 0) {
702 		err_str = "sockinit: bad nca vnode ops template";
703 		socknca_vnodeops = NULL;
704 		goto failure;
705 	}
706 
707 	error = sosctp_init();
708 	if (error != 0) {
709 		err_str = NULL;
710 		goto failure;
711 	}
712 
713 	/*
714 	 * Create sonode caches.  We create a special one for AF_UNIX so
715 	 * that we can track them for netstat(1m).
716 	 */
717 	socktpi_cache = kmem_cache_create("socktpi_cache",
718 	    sizeof (struct sonode), 0, socktpi_constructor,
719 	    socktpi_destructor, NULL, NULL, NULL, 0);
720 
721 	socktpi_unix_cache = kmem_cache_create("socktpi_unix_cache",
722 	    sizeof (struct sonode), 0, socktpi_unix_constructor,
723 	    socktpi_unix_destructor, NULL, NULL, NULL, 0);
724 
725 	/*
726 	 * Build initial list mapping socket parameters to vnode.
727 	 */
728 	rw_init(&splist_lock, NULL, RW_DEFAULT, NULL);
729 
730 	/*
731 	 * If sockets are needed before init runs /sbin/soconfig
732 	 * it is possible to preload the sockparams list here using
733 	 * calls like:
734 	 *	sockconfig(1,2,3, "/dev/tcp", 0);
735 	 */
736 
737 	/*
738 	 * Create a unique dev_t for use in so_fsid.
739 	 */
740 
741 	if ((dev = getudev()) == (major_t)-1)
742 		dev = 0;
743 	sockdev = makedevice(dev, 0);
744 
745 	mutex_init(&socklist.sl_lock, NULL, MUTEX_DEFAULT, NULL);
746 	sonca_init();
747 	sendfile_init();
748 	nl7c_init();
749 
750 	return (0);
751 
752 failure:
753 	(void) vfs_freevfsops_by_type(fstype);
754 	if (socktpi_vnodeops != NULL)
755 		vn_freevnodeops(socktpi_vnodeops);
756 	if (socknca_vnodeops != NULL)
757 		vn_freevnodeops(socknca_vnodeops);
758 	if (err_str != NULL)
759 		cmn_err(CE_WARN, err_str);
760 	return (error);
761 }
762 
763 /*
764  * Caller must hold the mutex. Used to set SOLOCKED.
765  */
766 void
767 so_lock_single(struct sonode *so)
768 {
769 	ASSERT(MUTEX_HELD(&so->so_lock));
770 
771 	while (so->so_flag & (SOLOCKED | SOASYNC_UNBIND)) {
772 		so->so_flag |= SOWANT;
773 		cv_wait_stop(&so->so_want_cv, &so->so_lock,
774 			SO_LOCK_WAKEUP_TIME);
775 	}
776 	so->so_flag |= SOLOCKED;
777 }
778 
779 /*
780  * Caller must hold the mutex and pass in SOLOCKED or SOASYNC_UNBIND.
781  * Used to clear SOLOCKED or SOASYNC_UNBIND.
782  */
783 void
784 so_unlock_single(struct sonode *so, int flag)
785 {
786 	ASSERT(MUTEX_HELD(&so->so_lock));
787 	ASSERT(flag & (SOLOCKED|SOASYNC_UNBIND));
788 	ASSERT((flag & ~(SOLOCKED|SOASYNC_UNBIND)) == 0);
789 	ASSERT(so->so_flag & flag);
790 
791 	/*
792 	 * Process the T_DISCON_IND on so_discon_ind_mp.
793 	 *
794 	 * Call to so_drain_discon_ind will result in so_lock
795 	 * being dropped and re-acquired later.
796 	 */
797 	if (so->so_discon_ind_mp != NULL)
798 		so_drain_discon_ind(so);
799 
800 	if (so->so_flag & SOWANT)
801 		cv_broadcast(&so->so_want_cv);
802 	so->so_flag &= ~(SOWANT|flag);
803 }
804 
805 /*
806  * Caller must hold the mutex. Used to set SOREADLOCKED.
807  * If the caller wants nonblocking behavior it should set fmode.
808  */
809 int
810 so_lock_read(struct sonode *so, int fmode)
811 {
812 	ASSERT(MUTEX_HELD(&so->so_lock));
813 
814 	while (so->so_flag & SOREADLOCKED) {
815 		if (fmode & (FNDELAY|FNONBLOCK))
816 			return (EWOULDBLOCK);
817 		so->so_flag |= SOWANT;
818 		cv_wait_stop(&so->so_want_cv, &so->so_lock,
819 			SO_LOCK_WAKEUP_TIME);
820 	}
821 	so->so_flag |= SOREADLOCKED;
822 	return (0);
823 }
824 
825 /*
826  * Like so_lock_read above but allows signals.
827  */
828 int
829 so_lock_read_intr(struct sonode *so, int fmode)
830 {
831 	ASSERT(MUTEX_HELD(&so->so_lock));
832 
833 	while (so->so_flag & SOREADLOCKED) {
834 		if (fmode & (FNDELAY|FNONBLOCK))
835 			return (EWOULDBLOCK);
836 		so->so_flag |= SOWANT;
837 		if (!cv_wait_sig(&so->so_want_cv, &so->so_lock))
838 			return (EINTR);
839 	}
840 	so->so_flag |= SOREADLOCKED;
841 	return (0);
842 }
843 
844 /*
845  * Caller must hold the mutex. Used to clear SOREADLOCKED,
846  * set in so_lock_read() or so_lock_read_intr().
847  */
848 void
849 so_unlock_read(struct sonode *so)
850 {
851 	ASSERT(MUTEX_HELD(&so->so_lock));
852 	ASSERT(so->so_flag & SOREADLOCKED);
853 
854 	if (so->so_flag & SOWANT)
855 		cv_broadcast(&so->so_want_cv);
856 	so->so_flag &= ~(SOWANT|SOREADLOCKED);
857 }
858 
859 /*
860  * Verify that the specified offset falls within the mblk and
861  * that the resulting pointer is aligned.
862  * Returns NULL if not.
863  */
864 void *
865 sogetoff(mblk_t *mp, t_uscalar_t offset,
866     t_uscalar_t length, uint_t align_size)
867 {
868 	uintptr_t ptr1, ptr2;
869 
870 	ASSERT(mp && mp->b_wptr >= mp->b_rptr);
871 	ptr1 = (uintptr_t)mp->b_rptr + offset;
872 	ptr2 = (uintptr_t)ptr1 + length;
873 	if (ptr1 < (uintptr_t)mp->b_rptr || ptr2 > (uintptr_t)mp->b_wptr) {
874 		eprintline(0);
875 		return (NULL);
876 	}
877 	if ((ptr1 & (align_size - 1)) != 0) {
878 		eprintline(0);
879 		return (NULL);
880 	}
881 	return ((void *)ptr1);
882 }
883 
884 /*
885  * Return the AF_UNIX underlying filesystem vnode matching a given name.
886  * Makes sure the sending and the destination sonodes are compatible.
887  * The vnode is returned held.
888  *
889  * The underlying filesystem VSOCK vnode has a v_stream pointer that
890  * references the actual stream head (hence indirectly the actual sonode).
891  */
892 static int
893 so_ux_lookup(struct sonode *so, struct sockaddr_un *soun, int checkaccess,
894 		vnode_t **vpp)
895 {
896 	vnode_t		*vp;	/* Underlying filesystem vnode */
897 	vnode_t		*svp;	/* sockfs vnode */
898 	struct sonode	*so2;
899 	int		error;
900 
901 	dprintso(so, 1, ("so_ux_lookup(%p) name <%s>\n",
902 		so, soun->sun_path));
903 
904 	error = lookupname(soun->sun_path, UIO_SYSSPACE, FOLLOW, NULLVPP, &vp);
905 	if (error) {
906 		eprintsoline(so, error);
907 		return (error);
908 	}
909 	if (vp->v_type != VSOCK) {
910 		error = ENOTSOCK;
911 		eprintsoline(so, error);
912 		goto done2;
913 	}
914 
915 	if (checkaccess) {
916 		/*
917 		 * Check that we have permissions to access the destination
918 		 * vnode. This check is not done in BSD but it is required
919 		 * by X/Open.
920 		 */
921 		if (error = VOP_ACCESS(vp, VREAD|VWRITE, 0, CRED())) {
922 			eprintsoline(so, error);
923 			goto done2;
924 		}
925 	}
926 
927 	/*
928 	 * Check if the remote socket has been closed.
929 	 *
930 	 * Synchronize with vn_rele_stream by holding v_lock while traversing
931 	 * v_stream->sd_vnode.
932 	 */
933 	mutex_enter(&vp->v_lock);
934 	if (vp->v_stream == NULL) {
935 		mutex_exit(&vp->v_lock);
936 		if (so->so_type == SOCK_DGRAM)
937 			error = EDESTADDRREQ;
938 		else
939 			error = ECONNREFUSED;
940 
941 		eprintsoline(so, error);
942 		goto done2;
943 	}
944 	ASSERT(vp->v_stream->sd_vnode);
945 	svp = vp->v_stream->sd_vnode;
946 	/*
947 	 * holding v_lock on underlying filesystem vnode and acquiring
948 	 * it on sockfs vnode. Assumes that no code ever attempts to
949 	 * acquire these locks in the reverse order.
950 	 */
951 	VN_HOLD(svp);
952 	mutex_exit(&vp->v_lock);
953 
954 	if (svp->v_type != VSOCK) {
955 		error = ENOTSOCK;
956 		eprintsoline(so, error);
957 		goto done;
958 	}
959 
960 	so2 = VTOSO(svp);
961 
962 	if (so->so_type != so2->so_type) {
963 		error = EPROTOTYPE;
964 		eprintsoline(so, error);
965 		goto done;
966 	}
967 
968 	VN_RELE(svp);
969 	*vpp = vp;
970 	return (0);
971 
972 done:
973 	VN_RELE(svp);
974 done2:
975 	VN_RELE(vp);
976 	return (error);
977 }
978 
979 /*
980  * Verify peer address for connect and sendto/sendmsg.
981  * Since sendto/sendmsg would not get synchronous errors from the transport
982  * provider we have to do these ugly checks in the socket layer to
983  * preserve compatibility with SunOS 4.X.
984  */
985 int
986 so_addr_verify(struct sonode *so, const struct sockaddr *name,
987     socklen_t namelen)
988 {
989 	int		family;
990 
991 	dprintso(so, 1, ("so_addr_verify(%p, %p, %d)\n", so, name, namelen));
992 
993 	ASSERT(name != NULL);
994 
995 	family = so->so_family;
996 	switch (family) {
997 	case AF_INET:
998 		if (name->sa_family != family) {
999 			eprintsoline(so, EAFNOSUPPORT);
1000 			return (EAFNOSUPPORT);
1001 		}
1002 		if (namelen != (socklen_t)sizeof (struct sockaddr_in)) {
1003 			eprintsoline(so, EINVAL);
1004 			return (EINVAL);
1005 		}
1006 		break;
1007 	case AF_INET6: {
1008 #ifdef DEBUG
1009 		struct sockaddr_in6 *sin6;
1010 #endif /* DEBUG */
1011 
1012 		if (name->sa_family != family) {
1013 			eprintsoline(so, EAFNOSUPPORT);
1014 			return (EAFNOSUPPORT);
1015 		}
1016 		if (namelen != (socklen_t)sizeof (struct sockaddr_in6)) {
1017 			eprintsoline(so, EINVAL);
1018 			return (EINVAL);
1019 		}
1020 #ifdef DEBUG
1021 		/* Verify that apps don't forget to clear sin6_scope_id etc */
1022 		sin6 = (struct sockaddr_in6 *)name;
1023 		if (sin6->sin6_scope_id != 0 &&
1024 		    !IN6_IS_ADDR_LINKSCOPE(&sin6->sin6_addr)) {
1025 			cmn_err(CE_WARN,
1026 			    "connect/send* with uninitialized sin6_scope_id "
1027 			    "(%d) on socket. Pid = %d\n",
1028 			    (int)sin6->sin6_scope_id, (int)curproc->p_pid);
1029 		}
1030 #endif /* DEBUG */
1031 		break;
1032 	}
1033 	case AF_UNIX:
1034 		if (so->so_state & SS_FADDR_NOXLATE) {
1035 			return (0);
1036 		}
1037 		if (namelen < (socklen_t)sizeof (short)) {
1038 			eprintsoline(so, ENOENT);
1039 			return (ENOENT);
1040 		}
1041 		if (name->sa_family != family) {
1042 			eprintsoline(so, EAFNOSUPPORT);
1043 			return (EAFNOSUPPORT);
1044 		}
1045 		/* MAXPATHLEN + soun_family + nul termination */
1046 		if (namelen > (socklen_t)(MAXPATHLEN + sizeof (short) + 1)) {
1047 			eprintsoline(so, ENAMETOOLONG);
1048 			return (ENAMETOOLONG);
1049 		}
1050 
1051 		break;
1052 
1053 	default:
1054 		/*
1055 		 * Default is don't do any length or sa_family check
1056 		 * to allow non-sockaddr style addresses.
1057 		 */
1058 		break;
1059 	}
1060 
1061 	return (0);
1062 }
1063 
1064 
1065 /*
1066  * Translate an AF_UNIX sockaddr_un to the transport internal name.
1067  * Assumes caller has called so_addr_verify first.
1068  */
1069 /*ARGSUSED*/
1070 int
1071 so_ux_addr_xlate(struct sonode *so, struct sockaddr *name,
1072     socklen_t namelen, int checkaccess,
1073     void **addrp, socklen_t *addrlenp)
1074 {
1075 	int			error;
1076 	struct sockaddr_un	*soun;
1077 	vnode_t			*vp;
1078 	void			*addr;
1079 	socklen_t		addrlen;
1080 
1081 	dprintso(so, 1, ("so_ux_addr_xlate(%p, %p, %d, %d)\n",
1082 			so, name, namelen, checkaccess));
1083 
1084 	ASSERT(name != NULL);
1085 	ASSERT(so->so_family == AF_UNIX);
1086 	ASSERT(!(so->so_state & SS_FADDR_NOXLATE));
1087 	ASSERT(namelen >= (socklen_t)sizeof (short));
1088 	ASSERT(name->sa_family == AF_UNIX);
1089 	soun = (struct sockaddr_un *)name;
1090 	/*
1091 	 * Lookup vnode for the specified path name and verify that
1092 	 * it is a socket.
1093 	 */
1094 	error = so_ux_lookup(so, soun, checkaccess, &vp);
1095 	if (error) {
1096 		eprintsoline(so, error);
1097 		return (error);
1098 	}
1099 	/*
1100 	 * Use the address of the peer vnode as the address to send
1101 	 * to. We release the peer vnode here. In case it has been
1102 	 * closed by the time the T_CONN_REQ or T_UNIDATA_REQ reaches the
1103 	 * transport the message will get an error or be dropped.
1104 	 */
1105 	so->so_ux_faddr.soua_vp = vp;
1106 	so->so_ux_faddr.soua_magic = SOU_MAGIC_EXPLICIT;
1107 	addr = &so->so_ux_faddr;
1108 	addrlen = (socklen_t)sizeof (so->so_ux_faddr);
1109 	dprintso(so, 1, ("ux_xlate UNIX: addrlen %d, vp %p\n",
1110 				addrlen, vp));
1111 	VN_RELE(vp);
1112 	*addrp = addr;
1113 	*addrlenp = (socklen_t)addrlen;
1114 	return (0);
1115 }
1116 
1117 /*
1118  * Esballoc free function for messages that contain SO_FILEP option.
1119  * Decrement the reference count on the file pointers using closef.
1120  */
1121 void
1122 fdbuf_free(struct fdbuf *fdbuf)
1123 {
1124 	int	i;
1125 	struct file *fp;
1126 
1127 	dprint(1, ("fdbuf_free: %d fds\n", fdbuf->fd_numfd));
1128 	for (i = 0; i < fdbuf->fd_numfd; i++) {
1129 		/*
1130 		 * We need pointer size alignment for fd_fds. On a LP64
1131 		 * kernel, the required alignment is 8 bytes while
1132 		 * the option headers and values are only 4 bytes
1133 		 * aligned. So its safer to do a bcopy compared to
1134 		 * assigning fdbuf->fd_fds[i] to fp.
1135 		 */
1136 		bcopy((char *)&fdbuf->fd_fds[i], (char *)&fp, sizeof (fp));
1137 		dprint(1, ("fdbuf_free: [%d] = %p\n", i, fp));
1138 		(void) closef(fp);
1139 	}
1140 	if (fdbuf->fd_ebuf != NULL)
1141 		kmem_free(fdbuf->fd_ebuf, fdbuf->fd_ebuflen);
1142 	kmem_free(fdbuf, fdbuf->fd_size);
1143 }
1144 
1145 /*
1146  * Allocate an esballoc'ed message for use for AF_UNIX file descriptor
1147  * passing. Sleep waiting for memory unless catching a signal in strwaitbuf.
1148  */
1149 mblk_t *
1150 fdbuf_allocmsg(int size, struct fdbuf *fdbuf)
1151 {
1152 	void	*buf;
1153 	mblk_t	*mp;
1154 
1155 	dprint(1, ("fdbuf_allocmsg: size %d, %d fds\n", size, fdbuf->fd_numfd));
1156 	buf = kmem_alloc(size, KM_SLEEP);
1157 	fdbuf->fd_ebuf = (caddr_t)buf;
1158 	fdbuf->fd_ebuflen = size;
1159 	fdbuf->fd_frtn.free_func = fdbuf_free;
1160 	fdbuf->fd_frtn.free_arg = (caddr_t)fdbuf;
1161 
1162 	while ((mp = esballoc((unsigned char *)buf, size, BPRI_MED,
1163 	    &fdbuf->fd_frtn)) == NULL) {
1164 		if (strwaitbuf(sizeof (mblk_t), BPRI_MED) != 0) {
1165 			/*
1166 			 * Got EINTR - pass out NULL. Caller will
1167 			 * return something like ENOBUFS.
1168 			 * XXX could use an esballoc_wait() type function.
1169 			 */
1170 			eprintline(ENOBUFS);
1171 			return (NULL);
1172 		}
1173 	}
1174 	if (mp == NULL)
1175 		return (NULL);
1176 	mp->b_datap->db_type = M_PROTO;
1177 	return (mp);
1178 }
1179 
1180 /*
1181  * Extract file descriptors from a fdbuf.
1182  * Return list in rights/rightslen.
1183  */
1184 /*ARGSUSED*/
1185 static int
1186 fdbuf_extract(struct fdbuf *fdbuf, void *rights, int rightslen)
1187 {
1188 	int	i, fd;
1189 	int	*rp;
1190 	struct file *fp;
1191 	int	numfd;
1192 
1193 	dprint(1, ("fdbuf_extract: %d fds, len %d\n",
1194 		fdbuf->fd_numfd, rightslen));
1195 
1196 	numfd = fdbuf->fd_numfd;
1197 	ASSERT(rightslen == numfd * (int)sizeof (int));
1198 
1199 	/*
1200 	 * Allocate a file descriptor and increment the f_count.
1201 	 * The latter is needed since we always call fdbuf_free
1202 	 * which performs a closef.
1203 	 */
1204 	rp = (int *)rights;
1205 	for (i = 0; i < numfd; i++) {
1206 		if ((fd = ufalloc(0)) == -1)
1207 			goto cleanup;
1208 		/*
1209 		 * We need pointer size alignment for fd_fds. On a LP64
1210 		 * kernel, the required alignment is 8 bytes while
1211 		 * the option headers and values are only 4 bytes
1212 		 * aligned. So its safer to do a bcopy compared to
1213 		 * assigning fdbuf->fd_fds[i] to fp.
1214 		 */
1215 		bcopy((char *)&fdbuf->fd_fds[i], (char *)&fp, sizeof (fp));
1216 		mutex_enter(&fp->f_tlock);
1217 		fp->f_count++;
1218 		mutex_exit(&fp->f_tlock);
1219 		setf(fd, fp);
1220 		*rp++ = fd;
1221 #ifdef C2_AUDIT
1222 		if (audit_active)
1223 			audit_fdrecv(fd, fp);
1224 #endif
1225 		dprint(1, ("fdbuf_extract: [%d] = %d, %p refcnt %d\n",
1226 			i, fd, fp, fp->f_count));
1227 	}
1228 	return (0);
1229 
1230 cleanup:
1231 	/*
1232 	 * Undo whatever partial work the loop above has done.
1233 	 */
1234 	{
1235 		int j;
1236 
1237 		rp = (int *)rights;
1238 		for (j = 0; j < i; j++) {
1239 			dprint(0,
1240 			    ("fdbuf_extract: cleanup[%d] = %d\n", j, *rp));
1241 			(void) closeandsetf(*rp++, NULL);
1242 		}
1243 	}
1244 
1245 	return (EMFILE);
1246 }
1247 
1248 /*
1249  * Insert file descriptors into an fdbuf.
1250  * Returns a kmem_alloc'ed fdbuf. The fdbuf should be freed
1251  * by calling fdbuf_free().
1252  */
1253 int
1254 fdbuf_create(void *rights, int rightslen, struct fdbuf **fdbufp)
1255 {
1256 	int		numfd, i;
1257 	int		*fds;
1258 	struct file	*fp;
1259 	struct fdbuf	*fdbuf;
1260 	int		fdbufsize;
1261 
1262 	dprint(1, ("fdbuf_create: len %d\n", rightslen));
1263 
1264 	numfd = rightslen / (int)sizeof (int);
1265 
1266 	fdbufsize = (int)FDBUF_HDRSIZE + (numfd * (int)sizeof (struct file *));
1267 	fdbuf = kmem_alloc(fdbufsize, KM_SLEEP);
1268 	fdbuf->fd_size = fdbufsize;
1269 	fdbuf->fd_numfd = 0;
1270 	fdbuf->fd_ebuf = NULL;
1271 	fdbuf->fd_ebuflen = 0;
1272 	fds = (int *)rights;
1273 	for (i = 0; i < numfd; i++) {
1274 		if ((fp = getf(fds[i])) == NULL) {
1275 			fdbuf_free(fdbuf);
1276 			return (EBADF);
1277 		}
1278 		dprint(1, ("fdbuf_create: [%d] = %d, %p refcnt %d\n",
1279 			i, fds[i], fp, fp->f_count));
1280 		mutex_enter(&fp->f_tlock);
1281 		fp->f_count++;
1282 		mutex_exit(&fp->f_tlock);
1283 		/*
1284 		 * The maximum alignment for fdbuf (or any option header
1285 		 * and its value) it 4 bytes. On a LP64 kernel, the alignment
1286 		 * is not sufficient for pointers (fd_fds in this case). Since
1287 		 * we just did a kmem_alloc (we get a double word alignment),
1288 		 * we don't need to do anything on the send side (we loose
1289 		 * the double word alignment because fdbuf goes after an
1290 		 * option header (eg T_unitdata_req) which is only 4 byte
1291 		 * aligned). We take care of this when we extract the file
1292 		 * descriptor in fdbuf_extract or fdbuf_free.
1293 		 */
1294 		fdbuf->fd_fds[i] = fp;
1295 		fdbuf->fd_numfd++;
1296 		releasef(fds[i]);
1297 #ifdef C2_AUDIT
1298 		if (audit_active)
1299 			audit_fdsend(fds[i], fp, 0);
1300 #endif
1301 	}
1302 	*fdbufp = fdbuf;
1303 	return (0);
1304 }
1305 
1306 static int
1307 fdbuf_optlen(int rightslen)
1308 {
1309 	int numfd;
1310 
1311 	numfd = rightslen / (int)sizeof (int);
1312 
1313 	return ((int)FDBUF_HDRSIZE + (numfd * (int)sizeof (struct file *)));
1314 }
1315 
1316 static t_uscalar_t
1317 fdbuf_cmsglen(int fdbuflen)
1318 {
1319 	return (t_uscalar_t)((fdbuflen - FDBUF_HDRSIZE) /
1320 	    (int)sizeof (struct file *) * (int)sizeof (int));
1321 }
1322 
1323 
1324 /*
1325  * Return non-zero if the mblk and fdbuf are consistent.
1326  */
1327 static int
1328 fdbuf_verify(mblk_t *mp, struct fdbuf *fdbuf, int fdbuflen)
1329 {
1330 	if (fdbuflen >= FDBUF_HDRSIZE &&
1331 	    fdbuflen == fdbuf->fd_size) {
1332 		frtn_t *frp = mp->b_datap->db_frtnp;
1333 		/*
1334 		 * Check that the SO_FILEP portion of the
1335 		 * message has not been modified by
1336 		 * the loopback transport. The sending sockfs generates
1337 		 * a message that is esballoc'ed with the free function
1338 		 * being fdbuf_free() and where free_arg contains the
1339 		 * identical information as the SO_FILEP content.
1340 		 *
1341 		 * If any of these constraints are not satisfied we
1342 		 * silently ignore the option.
1343 		 */
1344 		ASSERT(mp);
1345 		if (frp != NULL &&
1346 		    frp->free_func == fdbuf_free &&
1347 		    frp->free_arg != NULL &&
1348 		    bcmp(frp->free_arg, fdbuf, fdbuflen) == 0) {
1349 			dprint(1, ("fdbuf_verify: fdbuf %p len %d\n",
1350 				fdbuf, fdbuflen));
1351 			return (1);
1352 		} else {
1353 			cmn_err(CE_WARN,
1354 			    "sockfs: mismatched fdbuf content (%p)",
1355 			    (void *)mp);
1356 			return (0);
1357 		}
1358 	} else {
1359 		cmn_err(CE_WARN,
1360 		    "sockfs: mismatched fdbuf len %d, %d\n",
1361 		    fdbuflen, fdbuf->fd_size);
1362 		return (0);
1363 	}
1364 }
1365 
1366 /*
1367  * When the file descriptors returned by sorecvmsg can not be passed
1368  * to the application this routine will cleanup the references on
1369  * the files. Start at startoff bytes into the buffer.
1370  */
1371 static void
1372 close_fds(void *fdbuf, int fdbuflen, int startoff)
1373 {
1374 	int *fds = (int *)fdbuf;
1375 	int numfd = fdbuflen / (int)sizeof (int);
1376 	int i;
1377 
1378 	dprint(1, ("close_fds(%p, %d, %d)\n", fdbuf, fdbuflen, startoff));
1379 
1380 	for (i = 0; i < numfd; i++) {
1381 		if (startoff < 0)
1382 			startoff = 0;
1383 		if (startoff < (int)sizeof (int)) {
1384 			/*
1385 			 * This file descriptor is partially or fully after
1386 			 * the offset
1387 			 */
1388 			dprint(0,
1389 			    ("close_fds: cleanup[%d] = %d\n", i, fds[i]));
1390 			(void) closeandsetf(fds[i], NULL);
1391 		}
1392 		startoff -= (int)sizeof (int);
1393 	}
1394 }
1395 
1396 /*
1397  * Close all file descriptors contained in the control part starting at
1398  * the startoffset.
1399  */
1400 void
1401 so_closefds(void *control, t_uscalar_t controllen, int oldflg,
1402     int startoff)
1403 {
1404 	struct cmsghdr *cmsg;
1405 
1406 	if (control == NULL)
1407 		return;
1408 
1409 	if (oldflg) {
1410 		close_fds(control, controllen, startoff);
1411 		return;
1412 	}
1413 	/* Scan control part for file descriptors. */
1414 	for (cmsg = (struct cmsghdr *)control;
1415 	    CMSG_VALID(cmsg, control, (uintptr_t)control + controllen);
1416 	    cmsg = CMSG_NEXT(cmsg)) {
1417 		if (cmsg->cmsg_level == SOL_SOCKET &&
1418 		    cmsg->cmsg_type == SCM_RIGHTS) {
1419 			close_fds(CMSG_CONTENT(cmsg),
1420 			    (int)CMSG_CONTENTLEN(cmsg),
1421 			    startoff - (int)sizeof (struct cmsghdr));
1422 		}
1423 		startoff -= cmsg->cmsg_len;
1424 	}
1425 }
1426 
1427 /*
1428  * Returns a pointer/length for the file descriptors contained
1429  * in the control buffer. Returns with *fdlenp == -1 if there are no
1430  * file descriptor options present. This is different than there being
1431  * a zero-length file descriptor option.
1432  * Fail if there are multiple SCM_RIGHT cmsgs.
1433  */
1434 int
1435 so_getfdopt(void *control, t_uscalar_t controllen, int oldflg,
1436     void **fdsp, int *fdlenp)
1437 {
1438 	struct cmsghdr *cmsg;
1439 	void *fds;
1440 	int fdlen;
1441 
1442 	if (control == NULL) {
1443 		*fdsp = NULL;
1444 		*fdlenp = -1;
1445 		return (0);
1446 	}
1447 
1448 	if (oldflg) {
1449 		*fdsp = control;
1450 		if (controllen == 0)
1451 			*fdlenp = -1;
1452 		else
1453 			*fdlenp = controllen;
1454 		dprint(1, ("so_getfdopt: old %d\n", *fdlenp));
1455 		return (0);
1456 	}
1457 
1458 	fds = NULL;
1459 	fdlen = 0;
1460 
1461 	for (cmsg = (struct cmsghdr *)control;
1462 	    CMSG_VALID(cmsg, control, (uintptr_t)control + controllen);
1463 	    cmsg = CMSG_NEXT(cmsg)) {
1464 		if (cmsg->cmsg_level == SOL_SOCKET &&
1465 		    cmsg->cmsg_type == SCM_RIGHTS) {
1466 			if (fds != NULL)
1467 				return (EINVAL);
1468 			fds = CMSG_CONTENT(cmsg);
1469 			fdlen = (int)CMSG_CONTENTLEN(cmsg);
1470 			dprint(1, ("so_getfdopt: new %lu\n",
1471 				(size_t)CMSG_CONTENTLEN(cmsg)));
1472 		}
1473 	}
1474 	if (fds == NULL) {
1475 		dprint(1, ("so_getfdopt: NONE\n"));
1476 		*fdlenp = -1;
1477 	} else
1478 		*fdlenp = fdlen;
1479 	*fdsp = fds;
1480 	return (0);
1481 }
1482 
1483 /*
1484  * Return the length of the options including any file descriptor options.
1485  */
1486 t_uscalar_t
1487 so_optlen(void *control, t_uscalar_t controllen, int oldflg)
1488 {
1489 	struct cmsghdr *cmsg;
1490 	t_uscalar_t optlen = 0;
1491 	t_uscalar_t len;
1492 
1493 	if (control == NULL)
1494 		return (0);
1495 
1496 	if (oldflg)
1497 		return ((t_uscalar_t)(sizeof (struct T_opthdr) +
1498 		    fdbuf_optlen(controllen)));
1499 
1500 	for (cmsg = (struct cmsghdr *)control;
1501 	    CMSG_VALID(cmsg, control, (uintptr_t)control + controllen);
1502 	    cmsg = CMSG_NEXT(cmsg)) {
1503 		if (cmsg->cmsg_level == SOL_SOCKET &&
1504 		    cmsg->cmsg_type == SCM_RIGHTS) {
1505 			len = fdbuf_optlen((int)CMSG_CONTENTLEN(cmsg));
1506 		} else {
1507 			len = (t_uscalar_t)CMSG_CONTENTLEN(cmsg);
1508 		}
1509 		optlen += (t_uscalar_t)(_TPI_ALIGN_TOPT(len) +
1510 		    sizeof (struct T_opthdr));
1511 	}
1512 	dprint(1, ("so_optlen: controllen %d, flg %d -> optlen %d\n",
1513 		controllen, oldflg, optlen));
1514 	return (optlen);
1515 }
1516 
1517 /*
1518  * Copy options from control to the mblk. Skip any file descriptor options.
1519  */
1520 void
1521 so_cmsg2opt(void *control, t_uscalar_t controllen, int oldflg, mblk_t *mp)
1522 {
1523 	struct T_opthdr toh;
1524 	struct cmsghdr *cmsg;
1525 
1526 	if (control == NULL)
1527 		return;
1528 
1529 	if (oldflg) {
1530 		/* No real options - caller has handled file descriptors */
1531 		return;
1532 	}
1533 	for (cmsg = (struct cmsghdr *)control;
1534 	    CMSG_VALID(cmsg, control, (uintptr_t)control + controllen);
1535 	    cmsg = CMSG_NEXT(cmsg)) {
1536 		/*
1537 		 * Note: The caller handles file descriptors prior
1538 		 * to calling this function.
1539 		 */
1540 		t_uscalar_t len;
1541 
1542 		if (cmsg->cmsg_level == SOL_SOCKET &&
1543 		    cmsg->cmsg_type == SCM_RIGHTS)
1544 			continue;
1545 
1546 		len = (t_uscalar_t)CMSG_CONTENTLEN(cmsg);
1547 		toh.level = cmsg->cmsg_level;
1548 		toh.name = cmsg->cmsg_type;
1549 		toh.len = len + (t_uscalar_t)sizeof (struct T_opthdr);
1550 		toh.status = 0;
1551 
1552 		soappendmsg(mp, &toh, sizeof (toh));
1553 		soappendmsg(mp, CMSG_CONTENT(cmsg), len);
1554 		mp->b_wptr += _TPI_ALIGN_TOPT(len) - len;
1555 		ASSERT(mp->b_wptr <= mp->b_datap->db_lim);
1556 	}
1557 }
1558 
1559 /*
1560  * Return the length of the control message derived from the options.
1561  * Exclude SO_SRCADDR and SO_UNIX_CLOSE options. Include SO_FILEP.
1562  * When oldflg is set only include SO_FILEP.
1563  */
1564 t_uscalar_t
1565 so_cmsglen(mblk_t *mp, void *opt, t_uscalar_t optlen, int oldflg)
1566 {
1567 	t_uscalar_t cmsglen = 0;
1568 	struct T_opthdr *tohp;
1569 	t_uscalar_t len;
1570 	t_uscalar_t last_roundup = 0;
1571 
1572 	ASSERT(__TPI_TOPT_ISALIGNED(opt));
1573 
1574 	for (tohp = (struct T_opthdr *)opt;
1575 	    tohp && _TPI_TOPT_VALID(tohp, opt, (uintptr_t)opt + optlen);
1576 	    tohp = _TPI_TOPT_NEXTHDR(opt, optlen, tohp)) {
1577 		dprint(1, ("so_cmsglen: level 0x%x, name %d, len %d\n",
1578 			tohp->level, tohp->name, tohp->len));
1579 		if (tohp->level == SOL_SOCKET &&
1580 		    (tohp->name == SO_SRCADDR ||
1581 		    tohp->name == SO_UNIX_CLOSE)) {
1582 			continue;
1583 		}
1584 		if (tohp->level == SOL_SOCKET && tohp->name == SO_FILEP) {
1585 			struct fdbuf *fdbuf;
1586 			int fdbuflen;
1587 
1588 			fdbuf = (struct fdbuf *)_TPI_TOPT_DATA(tohp);
1589 			fdbuflen = (int)_TPI_TOPT_DATALEN(tohp);
1590 
1591 			if (!fdbuf_verify(mp, fdbuf, fdbuflen))
1592 				continue;
1593 			if (oldflg) {
1594 				cmsglen += fdbuf_cmsglen(fdbuflen);
1595 				continue;
1596 			}
1597 			len = fdbuf_cmsglen(fdbuflen);
1598 		} else {
1599 			if (oldflg)
1600 				continue;
1601 			len = (t_uscalar_t)_TPI_TOPT_DATALEN(tohp);
1602 		}
1603 		/*
1604 		 * Exlucde roundup for last option to not set
1605 		 * MSG_CTRUNC when the cmsg fits but the padding doesn't fit.
1606 		 */
1607 		last_roundup = (t_uscalar_t)
1608 		    (ROUNDUP_cmsglen(len + (int)sizeof (struct cmsghdr)) -
1609 		    (len + (int)sizeof (struct cmsghdr)));
1610 		cmsglen += (t_uscalar_t)(len + (int)sizeof (struct cmsghdr)) +
1611 		    last_roundup;
1612 	}
1613 	cmsglen -= last_roundup;
1614 	dprint(1, ("so_cmsglen: optlen %d, flg %d -> cmsglen %d\n",
1615 		optlen, oldflg, cmsglen));
1616 	return (cmsglen);
1617 }
1618 
1619 /*
1620  * Copy options from options to the control. Convert SO_FILEP to
1621  * file descriptors.
1622  * Returns errno or zero.
1623  */
1624 int
1625 so_opt2cmsg(mblk_t *mp, void *opt, t_uscalar_t optlen, int oldflg,
1626     void *control, t_uscalar_t controllen)
1627 {
1628 	struct T_opthdr *tohp;
1629 	struct cmsghdr *cmsg;
1630 	struct fdbuf *fdbuf;
1631 	int fdbuflen;
1632 	int error;
1633 
1634 	cmsg = (struct cmsghdr *)control;
1635 
1636 	ASSERT(__TPI_TOPT_ISALIGNED(opt));
1637 
1638 	for (tohp = (struct T_opthdr *)opt;
1639 	    tohp && _TPI_TOPT_VALID(tohp, opt, (uintptr_t)opt + optlen);
1640 	    tohp = _TPI_TOPT_NEXTHDR(opt, optlen, tohp)) {
1641 		dprint(1, ("so_opt2cmsg: level 0x%x, name %d, len %d\n",
1642 			tohp->level, tohp->name, tohp->len));
1643 
1644 		if (tohp->level == SOL_SOCKET &&
1645 		    (tohp->name == SO_SRCADDR ||
1646 		    tohp->name == SO_UNIX_CLOSE)) {
1647 			continue;
1648 		}
1649 		ASSERT((uintptr_t)cmsg <= (uintptr_t)control + controllen);
1650 		if (tohp->level == SOL_SOCKET && tohp->name == SO_FILEP) {
1651 			fdbuf = (struct fdbuf *)_TPI_TOPT_DATA(tohp);
1652 			fdbuflen = (int)_TPI_TOPT_DATALEN(tohp);
1653 
1654 			if (!fdbuf_verify(mp, fdbuf, fdbuflen))
1655 				return (EPROTO);
1656 			if (oldflg) {
1657 				error = fdbuf_extract(fdbuf, control,
1658 				    (int)controllen);
1659 				if (error != 0)
1660 					return (error);
1661 				continue;
1662 			} else {
1663 				int fdlen;
1664 
1665 				fdlen = (int)fdbuf_cmsglen(
1666 				    (int)_TPI_TOPT_DATALEN(tohp));
1667 
1668 				cmsg->cmsg_level = tohp->level;
1669 				cmsg->cmsg_type = SCM_RIGHTS;
1670 				cmsg->cmsg_len = (socklen_t)(fdlen +
1671 					sizeof (struct cmsghdr));
1672 
1673 				error = fdbuf_extract(fdbuf,
1674 						CMSG_CONTENT(cmsg), fdlen);
1675 				if (error != 0)
1676 					return (error);
1677 			}
1678 		} else {
1679 			if (oldflg)
1680 				continue;
1681 
1682 			cmsg->cmsg_level = tohp->level;
1683 			cmsg->cmsg_type = tohp->name;
1684 			cmsg->cmsg_len = (socklen_t)(_TPI_TOPT_DATALEN(tohp) +
1685 			    sizeof (struct cmsghdr));
1686 
1687 			/* copy content to control data part */
1688 			bcopy(&tohp[1], CMSG_CONTENT(cmsg),
1689 				CMSG_CONTENTLEN(cmsg));
1690 		}
1691 		/* move to next CMSG structure! */
1692 		cmsg = CMSG_NEXT(cmsg);
1693 	}
1694 	return (0);
1695 }
1696 
1697 /*
1698  * Extract the SO_SRCADDR option value if present.
1699  */
1700 void
1701 so_getopt_srcaddr(void *opt, t_uscalar_t optlen, void **srcp,
1702     t_uscalar_t *srclenp)
1703 {
1704 	struct T_opthdr		*tohp;
1705 
1706 	ASSERT(__TPI_TOPT_ISALIGNED(opt));
1707 
1708 	ASSERT(srcp != NULL && srclenp != NULL);
1709 	*srcp = NULL;
1710 	*srclenp = 0;
1711 
1712 	for (tohp = (struct T_opthdr *)opt;
1713 	    tohp && _TPI_TOPT_VALID(tohp, opt, (uintptr_t)opt + optlen);
1714 	    tohp = _TPI_TOPT_NEXTHDR(opt, optlen, tohp)) {
1715 		dprint(1, ("so_getopt_srcaddr: level 0x%x, name %d, len %d\n",
1716 			tohp->level, tohp->name, tohp->len));
1717 		if (tohp->level == SOL_SOCKET &&
1718 		    tohp->name == SO_SRCADDR) {
1719 			*srcp = _TPI_TOPT_DATA(tohp);
1720 			*srclenp = (t_uscalar_t)_TPI_TOPT_DATALEN(tohp);
1721 		}
1722 	}
1723 }
1724 
1725 /*
1726  * Verify if the SO_UNIX_CLOSE option is present.
1727  */
1728 int
1729 so_getopt_unix_close(void *opt, t_uscalar_t optlen)
1730 {
1731 	struct T_opthdr		*tohp;
1732 
1733 	ASSERT(__TPI_TOPT_ISALIGNED(opt));
1734 
1735 	for (tohp = (struct T_opthdr *)opt;
1736 	    tohp && _TPI_TOPT_VALID(tohp, opt, (uintptr_t)opt + optlen);
1737 	    tohp = _TPI_TOPT_NEXTHDR(opt, optlen, tohp)) {
1738 		dprint(1,
1739 			("so_getopt_unix_close: level 0x%x, name %d, len %d\n",
1740 			tohp->level, tohp->name, tohp->len));
1741 		if (tohp->level == SOL_SOCKET &&
1742 		    tohp->name == SO_UNIX_CLOSE)
1743 			return (1);
1744 	}
1745 	return (0);
1746 }
1747 
1748 /*
1749  * Allocate an M_PROTO message.
1750  *
1751  * If allocation fails the behavior depends on sleepflg:
1752  *	_ALLOC_NOSLEEP	fail immediately
1753  *	_ALLOC_INTR	sleep for memory until a signal is caught
1754  *	_ALLOC_SLEEP	sleep forever. Don't return NULL.
1755  */
1756 mblk_t *
1757 soallocproto(size_t size, int sleepflg)
1758 {
1759 	mblk_t	*mp;
1760 
1761 	/* Round up size for reuse */
1762 	size = MAX(size, 64);
1763 	mp = allocb(size, BPRI_MED);
1764 	if (mp == NULL) {
1765 		int error;	/* Dummy - error not returned to caller */
1766 
1767 		switch (sleepflg) {
1768 		case _ALLOC_SLEEP:
1769 			mp = allocb_wait(size, BPRI_MED, STR_NOSIG, &error);
1770 			ASSERT(mp);
1771 			break;
1772 		case _ALLOC_INTR:
1773 			mp = allocb_wait(size, BPRI_MED, 0, &error);
1774 			if (mp == NULL) {
1775 				/* Caught signal while sleeping for memory */
1776 				eprintline(ENOBUFS);
1777 				return (NULL);
1778 			}
1779 			break;
1780 		case _ALLOC_NOSLEEP:
1781 		default:
1782 			eprintline(ENOBUFS);
1783 			return (NULL);
1784 		}
1785 	}
1786 	DB_TYPE(mp) = M_PROTO;
1787 	return (mp);
1788 }
1789 
1790 /*
1791  * Allocate an M_PROTO message with a single component.
1792  * len is the length of buf. size is the amount to allocate.
1793  *
1794  * buf can be NULL with a non-zero len.
1795  * This results in a bzero'ed chunk being placed the message.
1796  */
1797 mblk_t *
1798 soallocproto1(const void *buf, ssize_t len, ssize_t size, int sleepflg)
1799 {
1800 	mblk_t	*mp;
1801 
1802 	if (size == 0)
1803 		size = len;
1804 
1805 	ASSERT(size >= len);
1806 	/* Round up size for reuse */
1807 	size = MAX(size, 64);
1808 	mp = soallocproto(size, sleepflg);
1809 	if (mp == NULL)
1810 		return (NULL);
1811 	mp->b_datap->db_type = M_PROTO;
1812 	if (len != 0) {
1813 		if (buf != NULL)
1814 			bcopy(buf, mp->b_wptr, len);
1815 		else
1816 			bzero(mp->b_wptr, len);
1817 		mp->b_wptr += len;
1818 	}
1819 	return (mp);
1820 }
1821 
1822 /*
1823  * Append buf/len to mp.
1824  * The caller has to ensure that there is enough room in the mblk.
1825  *
1826  * buf can be NULL with a non-zero len.
1827  * This results in a bzero'ed chunk being placed the message.
1828  */
1829 void
1830 soappendmsg(mblk_t *mp, const void *buf, ssize_t len)
1831 {
1832 	ASSERT(mp);
1833 
1834 	if (len != 0) {
1835 		/* Assert for room left */
1836 		ASSERT(mp->b_datap->db_lim - mp->b_wptr >= len);
1837 		if (buf != NULL)
1838 			bcopy(buf, mp->b_wptr, len);
1839 		else
1840 			bzero(mp->b_wptr, len);
1841 	}
1842 	mp->b_wptr += len;
1843 }
1844 
1845 /*
1846  * Create a message using two kernel buffers.
1847  * If size is set that will determine the allocation size (e.g. for future
1848  * soappendmsg calls). If size is zero it is derived from the buffer
1849  * lengths.
1850  */
1851 mblk_t *
1852 soallocproto2(const void *buf1, ssize_t len1, const void *buf2, ssize_t len2,
1853     ssize_t size, int sleepflg)
1854 {
1855 	mblk_t *mp;
1856 
1857 	if (size == 0)
1858 		size = len1 + len2;
1859 	ASSERT(size >= len1 + len2);
1860 
1861 	mp = soallocproto1(buf1, len1, size, sleepflg);
1862 	if (mp)
1863 		soappendmsg(mp, buf2, len2);
1864 	return (mp);
1865 }
1866 
1867 /*
1868  * Create a message using three kernel buffers.
1869  * If size is set that will determine the allocation size (for future
1870  * soappendmsg calls). If size is zero it is derived from the buffer
1871  * lengths.
1872  */
1873 mblk_t *
1874 soallocproto3(const void *buf1, ssize_t len1, const void *buf2, ssize_t len2,
1875     const void *buf3, ssize_t len3, ssize_t size, int sleepflg)
1876 {
1877 	mblk_t *mp;
1878 
1879 	if (size == 0)
1880 		size = len1 + len2 +len3;
1881 	ASSERT(size >= len1 + len2 + len3);
1882 
1883 	mp = soallocproto1(buf1, len1, size, sleepflg);
1884 	if (mp != NULL) {
1885 		soappendmsg(mp, buf2, len2);
1886 		soappendmsg(mp, buf3, len3);
1887 	}
1888 	return (mp);
1889 }
1890 
1891 #ifdef DEBUG
1892 char *
1893 pr_state(uint_t state, uint_t mode)
1894 {
1895 	static char buf[1024];
1896 
1897 	buf[0] = 0;
1898 	if (state & SS_ISCONNECTED)
1899 		strcat(buf, "ISCONNECTED ");
1900 	if (state & SS_ISCONNECTING)
1901 		strcat(buf, "ISCONNECTING ");
1902 	if (state & SS_ISDISCONNECTING)
1903 		strcat(buf, "ISDISCONNECTING ");
1904 	if (state & SS_CANTSENDMORE)
1905 		strcat(buf, "CANTSENDMORE ");
1906 
1907 	if (state & SS_CANTRCVMORE)
1908 		strcat(buf, "CANTRCVMORE ");
1909 	if (state & SS_ISBOUND)
1910 		strcat(buf, "ISBOUND ");
1911 	if (state & SS_NDELAY)
1912 		strcat(buf, "NDELAY ");
1913 	if (state & SS_NONBLOCK)
1914 		strcat(buf, "NONBLOCK ");
1915 
1916 	if (state & SS_ASYNC)
1917 		strcat(buf, "ASYNC ");
1918 	if (state & SS_ACCEPTCONN)
1919 		strcat(buf, "ACCEPTCONN ");
1920 	if (state & SS_HASCONNIND)
1921 		strcat(buf, "HASCONNIND ");
1922 	if (state & SS_SAVEDEOR)
1923 		strcat(buf, "SAVEDEOR ");
1924 
1925 	if (state & SS_RCVATMARK)
1926 		strcat(buf, "RCVATMARK ");
1927 	if (state & SS_OOBPEND)
1928 		strcat(buf, "OOBPEND ");
1929 	if (state & SS_HAVEOOBDATA)
1930 		strcat(buf, "HAVEOOBDATA ");
1931 	if (state & SS_HADOOBDATA)
1932 		strcat(buf, "HADOOBDATA ");
1933 
1934 	if (state & SS_FADDR_NOXLATE)
1935 		strcat(buf, "FADDR_NOXLATE ");
1936 
1937 	if (mode & SM_PRIV)
1938 		strcat(buf, "PRIV ");
1939 	if (mode & SM_ATOMIC)
1940 		strcat(buf, "ATOMIC ");
1941 	if (mode & SM_ADDR)
1942 		strcat(buf, "ADDR ");
1943 	if (mode & SM_CONNREQUIRED)
1944 		strcat(buf, "CONNREQUIRED ");
1945 
1946 	if (mode & SM_FDPASSING)
1947 		strcat(buf, "FDPASSING ");
1948 	if (mode & SM_EXDATA)
1949 		strcat(buf, "EXDATA ");
1950 	if (mode & SM_OPTDATA)
1951 		strcat(buf, "OPTDATA ");
1952 	if (mode & SM_BYTESTREAM)
1953 		strcat(buf, "BYTESTREAM ");
1954 	return (buf);
1955 }
1956 
1957 char *
1958 pr_addr(int family, struct sockaddr *addr, t_uscalar_t addrlen)
1959 {
1960 	static char buf[1024];
1961 
1962 	if (addr == NULL || addrlen == 0) {
1963 		sprintf(buf, "(len %d) %p", addrlen, addr);
1964 		return (buf);
1965 	}
1966 	switch (family) {
1967 	case AF_INET: {
1968 		struct sockaddr_in sin;
1969 
1970 		bcopy(addr, &sin, sizeof (sin));
1971 
1972 		(void) sprintf(buf, "(len %d) %x/%d",
1973 			addrlen, ntohl(sin.sin_addr.s_addr),
1974 			ntohs(sin.sin_port));
1975 		break;
1976 	}
1977 	case AF_INET6: {
1978 		struct sockaddr_in6 sin6;
1979 		uint16_t *piece = (uint16_t *)&sin6.sin6_addr;
1980 
1981 		bcopy((char *)addr, (char *)&sin6, sizeof (sin6));
1982 		sprintf(buf, "(len %d) %x:%x:%x:%x:%x:%x:%x:%x/%d",
1983 		    addrlen,
1984 		    ntohs(piece[0]), ntohs(piece[1]),
1985 		    ntohs(piece[2]), ntohs(piece[3]),
1986 		    ntohs(piece[4]), ntohs(piece[5]),
1987 		    ntohs(piece[6]), ntohs(piece[7]),
1988 		    ntohs(sin6.sin6_port));
1989 		break;
1990 	}
1991 	case AF_UNIX: {
1992 		struct sockaddr_un *soun = (struct sockaddr_un *)addr;
1993 
1994 		(void) sprintf(buf, "(len %d) %s",
1995 			addrlen,
1996 			(soun == NULL) ? "(none)" : soun->sun_path);
1997 		break;
1998 	}
1999 	default:
2000 		(void) sprintf(buf, "(unknown af %d)", family);
2001 		break;
2002 	}
2003 	return (buf);
2004 }
2005 
2006 /* The logical equivalence operator (a if-and-only-if b) */
2007 #define	EQUIV(a, b)	(((a) && (b)) || (!(a) && (!(b))))
2008 
2009 /*
2010  * Verify limitations and invariants on oob state.
2011  * Return 1 if OK, otherwise 0 so that it can be used as
2012  *	ASSERT(verify_oobstate(so));
2013  */
2014 int
2015 so_verify_oobstate(struct sonode *so)
2016 {
2017 	ASSERT(MUTEX_HELD(&so->so_lock));
2018 
2019 	/*
2020 	 * The possible state combinations are:
2021 	 *	0
2022 	 *	SS_OOBPEND
2023 	 *	SS_OOBPEND|SS_HAVEOOBDATA
2024 	 *	SS_OOBPEND|SS_HADOOBDATA
2025 	 *	SS_HADOOBDATA
2026 	 */
2027 	switch (so->so_state & (SS_OOBPEND|SS_HAVEOOBDATA|SS_HADOOBDATA)) {
2028 	case 0:
2029 	case SS_OOBPEND:
2030 	case SS_OOBPEND|SS_HAVEOOBDATA:
2031 	case SS_OOBPEND|SS_HADOOBDATA:
2032 	case SS_HADOOBDATA:
2033 		break;
2034 	default:
2035 		printf("Bad oob state 1 (%p): counts %d/%d state %s\n",
2036 			so, so->so_oobsigcnt,
2037 			so->so_oobcnt, pr_state(so->so_state, so->so_mode));
2038 		return (0);
2039 	}
2040 
2041 	/* SS_RCVATMARK should only be set when SS_OOBPEND is set */
2042 	if ((so->so_state & (SS_RCVATMARK|SS_OOBPEND)) == SS_RCVATMARK) {
2043 		printf("Bad oob state 2 (%p): counts %d/%d state %s\n",
2044 			so, so->so_oobsigcnt,
2045 			so->so_oobcnt, pr_state(so->so_state, so->so_mode));
2046 		return (0);
2047 	}
2048 
2049 	/*
2050 	 * (so_oobsigcnt != 0 or SS_RCVATMARK) iff SS_OOBPEND
2051 	 */
2052 	if (!EQUIV((so->so_oobsigcnt != 0) || (so->so_state & SS_RCVATMARK),
2053 		so->so_state & SS_OOBPEND)) {
2054 		printf("Bad oob state 3 (%p): counts %d/%d state %s\n",
2055 			so, so->so_oobsigcnt,
2056 			so->so_oobcnt, pr_state(so->so_state, so->so_mode));
2057 		return (0);
2058 	}
2059 
2060 	/*
2061 	 * Unless SO_OOBINLINE we have so_oobmsg != NULL iff SS_HAVEOOBDATA
2062 	 */
2063 	if (!(so->so_options & SO_OOBINLINE) &&
2064 	    !EQUIV(so->so_oobmsg != NULL, so->so_state & SS_HAVEOOBDATA)) {
2065 		printf("Bad oob state 4 (%p): counts %d/%d state %s\n",
2066 			so, so->so_oobsigcnt,
2067 			so->so_oobcnt, pr_state(so->so_state, so->so_mode));
2068 		return (0);
2069 	}
2070 	if (so->so_oobsigcnt < so->so_oobcnt) {
2071 		printf("Bad oob state 5 (%p): counts %d/%d state %s\n",
2072 			so, so->so_oobsigcnt,
2073 			so->so_oobcnt, pr_state(so->so_state, so->so_mode));
2074 		return (0);
2075 	}
2076 	return (1);
2077 }
2078 #undef	EQUIV
2079 
2080 #endif /* DEBUG */
2081 
2082 /* initialize sockfs zone specific kstat related items			*/
2083 void *
2084 sock_kstat_init(zoneid_t zoneid)
2085 {
2086 	kstat_t	*ksp;
2087 
2088 	ksp = kstat_create_zone("sockfs", 0, "sock_unix_list", "misc",
2089 	    KSTAT_TYPE_RAW, 0, KSTAT_FLAG_VAR_SIZE|KSTAT_FLAG_VIRTUAL, zoneid);
2090 
2091 	if (ksp != NULL) {
2092 		ksp->ks_update = sockfs_update;
2093 		ksp->ks_snapshot = sockfs_snapshot;
2094 		ksp->ks_lock = &socklist.sl_lock;
2095 		ksp->ks_private = (void *)(uintptr_t)zoneid;
2096 		kstat_install(ksp);
2097 	}
2098 
2099 	return (ksp);
2100 }
2101 
2102 /* tear down sockfs zone specific kstat related items			*/
2103 /*ARGSUSED*/
2104 void
2105 sock_kstat_fini(zoneid_t zoneid, void *arg)
2106 {
2107 	kstat_t *ksp = (kstat_t *)arg;
2108 
2109 	if (ksp != NULL) {
2110 		ASSERT(zoneid == (zoneid_t)(uintptr_t)ksp->ks_private);
2111 		kstat_delete(ksp);
2112 	}
2113 }
2114 
2115 /*
2116  * Zones:
2117  * Note that nactive is going to be different for each zone.
2118  * This means we require kstat to call sockfs_update and then sockfs_snapshot
2119  * for the same zone, or sockfs_snapshot will be taken into the wrong size
2120  * buffer. This is safe, but if the buffer is too small, user will not be
2121  * given details of all sockets. However, as this kstat has a ks_lock, kstat
2122  * driver will keep it locked between the update and the snapshot, so no
2123  * other process (zone) can currently get inbetween resulting in a wrong size
2124  * buffer allocation.
2125  */
2126 static int
2127 sockfs_update(kstat_t *ksp, int rw)
2128 {
2129 	uint_t	nactive = 0;		/* # of active AF_UNIX sockets	*/
2130 	struct sonode	*so;		/* current sonode on socklist	*/
2131 	zoneid_t	myzoneid = (zoneid_t)(uintptr_t)ksp->ks_private;
2132 
2133 	ASSERT((zoneid_t)(uintptr_t)ksp->ks_private == getzoneid());
2134 
2135 	if (rw == KSTAT_WRITE) {	/* bounce all writes		*/
2136 		return (EACCES);
2137 	}
2138 
2139 	for (so = socklist.sl_list; so != NULL; so = so->so_next) {
2140 		if (so->so_accessvp != NULL && so->so_zoneid == myzoneid) {
2141 			nactive++;
2142 		}
2143 	}
2144 	ksp->ks_ndata = nactive;
2145 	ksp->ks_data_size = nactive * sizeof (struct k_sockinfo);
2146 
2147 	return (0);
2148 }
2149 
2150 static int
2151 sockfs_snapshot(kstat_t *ksp, void *buf, int rw)
2152 {
2153 	int			ns;	/* # of sonodes we've copied	*/
2154 	struct sonode		*so;	/* current sonode on socklist	*/
2155 	struct k_sockinfo	*pksi;	/* where we put sockinfo data	*/
2156 	t_uscalar_t		sn_len;	/* soa_len			*/
2157 	zoneid_t		myzoneid = (zoneid_t)(uintptr_t)ksp->ks_private;
2158 
2159 	ASSERT((zoneid_t)(uintptr_t)ksp->ks_private == getzoneid());
2160 
2161 	ksp->ks_snaptime = gethrtime();
2162 
2163 	if (rw == KSTAT_WRITE) {	/* bounce all writes		*/
2164 		return (EACCES);
2165 	}
2166 
2167 	/*
2168 	 * for each sonode on the socklist, we massage the important
2169 	 * info into buf, in k_sockinfo format.
2170 	 */
2171 	pksi = (struct k_sockinfo *)buf;
2172 	for (ns = 0, so = socklist.sl_list; so != NULL; so = so->so_next) {
2173 		/* only stuff active sonodes and the same zone:		*/
2174 		if (so->so_accessvp == NULL || so->so_zoneid != myzoneid) {
2175 			continue;
2176 		}
2177 
2178 		/*
2179 		 * If the sonode was activated between the update and the
2180 		 * snapshot, we're done - as this is only a snapshot.
2181 		 */
2182 		if ((caddr_t)(pksi) >= (caddr_t)buf + ksp->ks_data_size) {
2183 			break;
2184 		}
2185 
2186 		/* copy important info into buf:			*/
2187 		pksi->ks_si.si_size = sizeof (struct k_sockinfo);
2188 		pksi->ks_si.si_family = so->so_family;
2189 		pksi->ks_si.si_type = so->so_type;
2190 		pksi->ks_si.si_flag = so->so_flag;
2191 		pksi->ks_si.si_state = so->so_state;
2192 		pksi->ks_si.si_serv_type = so->so_serv_type;
2193 		pksi->ks_si.si_ux_laddr_sou_magic = so->so_ux_laddr.soua_magic;
2194 		pksi->ks_si.si_ux_faddr_sou_magic = so->so_ux_faddr.soua_magic;
2195 		pksi->ks_si.si_laddr_soa_len = so->so_laddr.soa_len;
2196 		pksi->ks_si.si_faddr_soa_len = so->so_faddr.soa_len;
2197 		pksi->ks_si.si_szoneid = so->so_zoneid;
2198 
2199 		mutex_enter(&so->so_lock);
2200 
2201 		if (so->so_laddr_sa != NULL) {
2202 			ASSERT(so->so_laddr_sa->sa_data != NULL);
2203 			sn_len = so->so_laddr_len;
2204 			ASSERT(sn_len <= sizeof (short) +
2205 			    sizeof (pksi->ks_si.si_laddr_sun_path));
2206 
2207 			pksi->ks_si.si_laddr_family =
2208 				so->so_laddr_sa->sa_family;
2209 			if (sn_len != 0) {
2210 				/* AF_UNIX socket names are NULL terminated */
2211 				(void) strncpy(pksi->ks_si.si_laddr_sun_path,
2212 				    so->so_laddr_sa->sa_data,
2213 				    sizeof (pksi->ks_si.si_laddr_sun_path));
2214 				sn_len = strlen(pksi->ks_si.si_laddr_sun_path);
2215 			}
2216 			pksi->ks_si.si_laddr_sun_path[sn_len] = 0;
2217 		}
2218 
2219 		if (so->so_faddr_sa != NULL) {
2220 			ASSERT(so->so_faddr_sa->sa_data != NULL);
2221 			sn_len = so->so_faddr_len;
2222 			ASSERT(sn_len <= sizeof (short) +
2223 			    sizeof (pksi->ks_si.si_faddr_sun_path));
2224 
2225 			pksi->ks_si.si_faddr_family =
2226 			    so->so_faddr_sa->sa_family;
2227 			if (sn_len != 0) {
2228 				(void) strncpy(pksi->ks_si.si_faddr_sun_path,
2229 				    so->so_faddr_sa->sa_data,
2230 				    sizeof (pksi->ks_si.si_faddr_sun_path));
2231 				sn_len = strlen(pksi->ks_si.si_faddr_sun_path);
2232 			}
2233 			pksi->ks_si.si_faddr_sun_path[sn_len] = 0;
2234 		}
2235 
2236 		mutex_exit(&so->so_lock);
2237 
2238 		(void) sprintf(pksi->ks_straddr[0], "%p", (void *)so);
2239 		(void) sprintf(pksi->ks_straddr[1], "%p",
2240 		    (void *)so->so_ux_laddr.soua_vp);
2241 		(void) sprintf(pksi->ks_straddr[2], "%p",
2242 		    (void *)so->so_ux_faddr.soua_vp);
2243 
2244 		ns++;
2245 		pksi++;
2246 	}
2247 
2248 	ksp->ks_ndata = ns;
2249 	return (0);
2250 }
2251 
2252 ssize_t
2253 soreadfile(file_t *fp, uchar_t *buf, u_offset_t fileoff, int *err, size_t size)
2254 {
2255 	struct uio auio;
2256 	struct iovec aiov[MSG_MAXIOVLEN];
2257 	register vnode_t *vp;
2258 	int ioflag, rwflag;
2259 	ssize_t cnt;
2260 	int error = 0;
2261 	int iovcnt = 0;
2262 	short fflag;
2263 
2264 	vp = fp->f_vnode;
2265 	fflag = fp->f_flag;
2266 
2267 	rwflag = 0;
2268 	aiov[0].iov_base = (caddr_t)buf;
2269 	aiov[0].iov_len = size;
2270 	iovcnt = 1;
2271 	cnt = (ssize_t)size;
2272 	(void) VOP_RWLOCK(vp, rwflag, NULL);
2273 
2274 	auio.uio_loffset = fileoff;
2275 	auio.uio_iov = aiov;
2276 	auio.uio_iovcnt = iovcnt;
2277 	auio.uio_resid = cnt;
2278 	auio.uio_segflg = UIO_SYSSPACE;
2279 	auio.uio_llimit = MAXOFFSET_T;
2280 	auio.uio_fmode = fflag;
2281 	auio.uio_extflg = UIO_COPY_CACHED;
2282 
2283 	ioflag = auio.uio_fmode & (FAPPEND|FSYNC|FDSYNC|FRSYNC);
2284 
2285 	/* If read sync is not asked for, filter sync flags */
2286 	if ((ioflag & FRSYNC) == 0)
2287 		ioflag &= ~(FSYNC|FDSYNC);
2288 	error = VOP_READ(vp, &auio, ioflag, fp->f_cred, NULL);
2289 	cnt -= auio.uio_resid;
2290 
2291 	VOP_RWUNLOCK(vp, rwflag, NULL);
2292 
2293 	if (error == EINTR && cnt != 0)
2294 		error = 0;
2295 out:
2296 	if (error != 0) {
2297 		*err = error;
2298 		return (0);
2299 	} else {
2300 		*err = 0;
2301 		return (cnt);
2302 	}
2303 }
2304