1 /*-
2 * Copyright (c) 1982, 1986, 1989, 1991, 1993
3 * The Regents of the University of California.
4 * Copyright (c) 2004-2008 Robert N. M. Watson
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 4. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 *
31 * From: @(#)uipc_usrreq.c 8.3 (Berkeley) 1/4/94
32 */
33
34 /*
35 * UNIX Domain (Local) Sockets
36 *
37 * This is an implementation of UNIX (local) domain sockets. Each socket has
38 * an associated struct unpcb (UNIX protocol control block). Stream sockets
39 * may be connected to 0 or 1 other socket. Datagram sockets may be
40 * connected to 0, 1, or many other sockets. Sockets may be created and
41 * connected in pairs (socketpair(2)), or bound/connected to using the file
42 * system name space. For most purposes, only the receive socket buffer is
43 * used, as sending on one socket delivers directly to the receive socket
44 * buffer of a second socket.
45 *
46 * The implementation is substantially complicated by the fact that
47 * "ancillary data", such as file descriptors or credentials, may be passed
48 * across UNIX domain sockets. The potential for passing UNIX domain sockets
49 * over other UNIX domain sockets requires the implementation of a simple
50 * garbage collector to find and tear down cycles of disconnected sockets.
51 *
52 * TODO:
53 * SEQPACKET, RDM
54 * rethink name space problems
55 * need a proper out-of-band
56 */
57
58 #include <sys/cdefs.h>
59 __FBSDID("$FreeBSD$");
60
61 #include "opt_ddb.h"
62 #include "opt_mac.h"
63
64 #include <sys/param.h>
65 #include <sys/domain.h>
66 #include <sys/fcntl.h>
67 #include <sys/malloc.h> /* XXX must be before <sys/file.h> */
68 #include <sys/eventhandler.h>
69 #include <sys/file.h>
70 #include <sys/filedesc.h>
71 #include <sys/jail.h>
72 #include <sys/kernel.h>
73 #include <sys/lock.h>
74 #include <sys/mbuf.h>
75 #include <sys/mount.h>
76 #include <sys/mutex.h>
77 #include <sys/namei.h>
78 #include <sys/proc.h>
79 #include <sys/protosw.h>
80 #include <sys/resourcevar.h>
81 #include <sys/rwlock.h>
82 #include <sys/socket.h>
83 #include <sys/socketvar.h>
84 #include <sys/signalvar.h>
85 #include <sys/stat.h>
86 #include <sys/sx.h>
87 #include <sys/sysctl.h>
88 #include <sys/systm.h>
89 #include <sys/taskqueue.h>
90 #include <sys/un.h>
91 #include <sys/unpcb.h>
92 #include <sys/vnode.h>
93
94 #ifdef DDB
95 #include <ddb/ddb.h>
96 #endif
97
98 #include <security/mac/mac_framework.h>
99
100 #include <vm/uma.h>
101
102 static uma_zone_t unp_zone;
103 static unp_gen_t unp_gencnt;
104 static u_int unp_count; /* Count of local sockets. */
105 static ino_t unp_ino; /* Prototype for fake inode numbers. */
106 static int unp_rights; /* File descriptors in flight. */
107 static struct unp_head unp_shead; /* List of local stream sockets. */
108 static struct unp_head unp_dhead; /* List of local datagram sockets. */
109
110 static const struct sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
111
112 /*
113 * Garbage collection of cyclic file descriptor/socket references occurs
114 * asynchronously in a taskqueue context in order to avoid recursion and
115 * reentrance in the UNIX domain socket, file descriptor, and socket layer
116 * code. See unp_gc() for a full description.
117 */
118 static struct task unp_gc_task;
119
120 /*
121 * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
122 * stream sockets, although the total for sender and receiver is actually
123 * only PIPSIZ.
124 *
125 * Datagram sockets really use the sendspace as the maximum datagram size,
126 * and don't really want to reserve the sendspace. Their recvspace should be
127 * large enough for at least one max-size datagram plus address.
128 */
129 #ifndef PIPSIZ
130 #define PIPSIZ 8192
131 #endif
132 static u_long unpst_sendspace = PIPSIZ;
133 static u_long unpst_recvspace = PIPSIZ;
134 static u_long unpdg_sendspace = 2*1024; /* really max datagram size */
135 static u_long unpdg_recvspace = 4*1024;
136
137 SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW, 0, "Local domain");
138 SYSCTL_NODE(_net_local, SOCK_STREAM, stream, CTLFLAG_RW, 0, "SOCK_STREAM");
139 SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram, CTLFLAG_RW, 0, "SOCK_DGRAM");
140
141 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
142 &unpst_sendspace, 0, "");
143 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
144 &unpst_recvspace, 0, "");
145 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
146 &unpdg_sendspace, 0, "");
147 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
148 &unpdg_recvspace, 0, "");
149 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0, "");
150
151 /*-
152 * Locking and synchronization:
153 *
154 * The global UNIX domain socket rwlock (unp_global_rwlock) protects all
155 * global variables, including the linked lists tracking the set of allocated
156 * UNIX domain sockets. The global rwlock also serves to prevent deadlock
157 * when more than one PCB lock is acquired at a time (i.e., during
158 * connect()). Finally, the global rwlock protects uncounted references from
159 * vnodes to sockets bound to those vnodes: to safely dereference the
160 * v_socket pointer, the global rwlock must be held while a full reference is
161 * acquired.
162 *
163 * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
164 * allocated in pru_attach() and freed in pru_detach(). The validity of that
165 * pointer is an invariant, so no lock is required to dereference the so_pcb
166 * pointer if a valid socket reference is held by the caller. In practice,
167 * this is always true during operations performed on a socket. Each unpcb
168 * has a back-pointer to its socket, unp_socket, which will be stable under
169 * the same circumstances.
170 *
171 * This pointer may only be safely dereferenced as long as a valid reference
172 * to the unpcb is held. Typically, this reference will be from the socket,
173 * or from another unpcb when the referring unpcb's lock is held (in order
174 * that the reference not be invalidated during use). For example, to follow
175 * unp->unp_conn->unp_socket, you need unlock the lock on unp, not unp_conn,
176 * as unp_socket remains valid as long as the reference to unp_conn is valid.
177 *
178 * Fields of unpcbss are locked using a per-unpcb lock, unp_mtx. Individual
179 * atomic reads without the lock may be performed "lockless", but more
180 * complex reads and read-modify-writes require the mutex to be held. No
181 * lock order is defined between unpcb locks -- multiple unpcb locks may be
182 * acquired at the same time only when holding the global UNIX domain socket
183 * rwlock exclusively, which prevents deadlocks.
184 *
185 * Blocking with UNIX domain sockets is a tricky issue: unlike most network
186 * protocols, bind() is a non-atomic operation, and connect() requires
187 * potential sleeping in the protocol, due to potentially waiting on local or
188 * distributed file systems. We try to separate "lookup" operations, which
189 * may sleep, and the IPC operations themselves, which typically can occur
190 * with relative atomicity as locks can be held over the entire operation.
191 *
192 * Another tricky issue is simultaneous multi-threaded or multi-process
193 * access to a single UNIX domain socket. These are handled by the flags
194 * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
195 * binding, both of which involve dropping UNIX domain socket locks in order
196 * to perform namei() and other file system operations.
197 */
198 static struct rwlock unp_global_rwlock;
199
200 #define UNP_GLOBAL_LOCK_INIT() rw_init(&unp_global_rwlock, \
201 "unp_global_rwlock")
202
203 #define UNP_GLOBAL_LOCK_ASSERT() rw_assert(&unp_global_rwlock, \
204 RA_LOCKED)
205 #define UNP_GLOBAL_UNLOCK_ASSERT() rw_assert(&unp_global_rwlock, \
206 RA_UNLOCKED)
207
208 #define UNP_GLOBAL_WLOCK() rw_wlock(&unp_global_rwlock)
209 #define UNP_GLOBAL_WUNLOCK() rw_wunlock(&unp_global_rwlock)
210 #define UNP_GLOBAL_WLOCK_ASSERT() rw_assert(&unp_global_rwlock, \
211 RA_WLOCKED)
212 #define UNP_GLOBAL_WOWNED() rw_wowned(&unp_global_rwlock)
213
214 #define UNP_GLOBAL_RLOCK() rw_rlock(&unp_global_rwlock)
215 #define UNP_GLOBAL_RUNLOCK() rw_runlock(&unp_global_rwlock)
216 #define UNP_GLOBAL_RLOCK_ASSERT() rw_assert(&unp_global_rwlock, \
217 RA_RLOCKED)
218
219 #define UNP_PCB_LOCK_INIT(unp) mtx_init(&(unp)->unp_mtx, \
220 "unp_mtx", "unp_mtx", \
221 MTX_DUPOK|MTX_DEF|MTX_RECURSE)
222 #define UNP_PCB_LOCK_DESTROY(unp) mtx_destroy(&(unp)->unp_mtx)
223 #define UNP_PCB_LOCK(unp) mtx_lock(&(unp)->unp_mtx)
224 #define UNP_PCB_UNLOCK(unp) mtx_unlock(&(unp)->unp_mtx)
225 #define UNP_PCB_LOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_OWNED)
226
227 static int uipc_connect2(struct socket *, struct socket *);
228 static int uipc_ctloutput(struct socket *, struct sockopt *);
229 static int unp_connect(struct socket *, struct sockaddr *,
230 struct thread *);
231 static int unp_connect2(struct socket *so, struct socket *so2, int);
232 static void unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
233 static void unp_dispose(struct mbuf *);
234 static void unp_shutdown(struct unpcb *);
235 static void unp_drop(struct unpcb *, int);
236 static void unp_gc(__unused void *, int);
237 static void unp_scan(struct mbuf *, void (*)(struct file *));
238 static void unp_mark(struct file *);
239 static void unp_discard(struct file *);
240 static void unp_freerights(struct file **, int);
241 static void unp_init(void);
242 static int unp_internalize(struct mbuf **, struct thread *);
243 static int unp_externalize(struct mbuf *, struct mbuf **);
244 static struct mbuf *unp_addsockcred(struct thread *, struct mbuf *);
245
246 /*
247 * Definitions of protocols supported in the LOCAL domain.
248 */
249 static struct domain localdomain;
250 static struct pr_usrreqs uipc_usrreqs;
251 static struct protosw localsw[] = {
252 {
253 .pr_type = SOCK_STREAM,
254 .pr_domain = &localdomain,
255 .pr_flags = PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
256 .pr_ctloutput = &uipc_ctloutput,
257 .pr_usrreqs = &uipc_usrreqs
258 },
259 {
260 .pr_type = SOCK_DGRAM,
261 .pr_domain = &localdomain,
262 .pr_flags = PR_ATOMIC|PR_ADDR|PR_RIGHTS,
263 .pr_usrreqs = &uipc_usrreqs
264 },
265 };
266
267 static struct domain localdomain = {
268 .dom_family = AF_LOCAL,
269 .dom_name = "local",
270 .dom_init = unp_init,
271 .dom_externalize = unp_externalize,
272 .dom_dispose = unp_dispose,
273 .dom_protosw = localsw,
274 .dom_protoswNPROTOSW = &localsw[sizeof(localsw)/sizeof(localsw[0])]
275 };
276 DOMAIN_SET(local);
277
278 static void
279 uipc_abort(struct socket *so)
280 {
281 struct unpcb *unp, *unp2;
282
283 unp = sotounpcb(so);
284 KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
285
286 UNP_GLOBAL_WLOCK();
287 UNP_PCB_LOCK(unp);
288 unp2 = unp->unp_conn;
289 if (unp2 != NULL) {
290 UNP_PCB_LOCK(unp2);
291 unp_drop(unp2, ECONNABORTED);
292 UNP_PCB_UNLOCK(unp2);
293 }
294 UNP_PCB_UNLOCK(unp);
295 UNP_GLOBAL_WUNLOCK();
296 }
297
298 static int
299 uipc_accept(struct socket *so, struct sockaddr **nam)
300 {
301 struct unpcb *unp, *unp2;
302 const struct sockaddr *sa;
303
304 /*
305 * Pass back name of connected socket, if it was bound and we are
306 * still connected (our peer may have closed already!).
307 */
308 unp = sotounpcb(so);
309 KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
310
311 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
312 UNP_GLOBAL_RLOCK();
313 unp2 = unp->unp_conn;
314 if (unp2 != NULL && unp2->unp_addr != NULL) {
315 UNP_PCB_LOCK(unp2);
316 sa = (struct sockaddr *) unp2->unp_addr;
317 bcopy(sa, *nam, sa->sa_len);
318 UNP_PCB_UNLOCK(unp2);
319 } else {
320 sa = &sun_noname;
321 bcopy(sa, *nam, sa->sa_len);
322 }
323 UNP_GLOBAL_RUNLOCK();
324 return (0);
325 }
326
327 static int
328 uipc_attach(struct socket *so, int proto, struct thread *td)
329 {
330 u_long sendspace, recvspace;
331 struct unpcb *unp;
332 int error, locked;
333
334 KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
335 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
336 switch (so->so_type) {
337 case SOCK_STREAM:
338 sendspace = unpst_sendspace;
339 recvspace = unpst_recvspace;
340 break;
341
342 case SOCK_DGRAM:
343 sendspace = unpdg_sendspace;
344 recvspace = unpdg_recvspace;
345 break;
346
347 default:
348 panic("uipc_attach");
349 }
350 error = soreserve(so, sendspace, recvspace);
351 if (error)
352 return (error);
353 }
354 unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
355 if (unp == NULL)
356 return (ENOBUFS);
357 LIST_INIT(&unp->unp_refs);
358 UNP_PCB_LOCK_INIT(unp);
359 unp->unp_socket = so;
360 so->so_pcb = unp;
361 unp->unp_refcount = 1;
362
363 /*
364 * uipc_attach() may be called indirectly from within the UNIX domain
365 * socket code via sonewconn() in unp_connect(). Since rwlocks can
366 * not be recursed, we do the closest thing.
367 */
368 locked = 0;
369 if (!UNP_GLOBAL_WOWNED()) {
370 UNP_GLOBAL_WLOCK();
371 locked = 1;
372 }
373 unp->unp_gencnt = ++unp_gencnt;
374 unp_count++;
375 LIST_INSERT_HEAD(so->so_type == SOCK_DGRAM ? &unp_dhead : &unp_shead,
376 unp, unp_link);
377 if (locked)
378 UNP_GLOBAL_WUNLOCK();
379
380 return (0);
381 }
382
383 static int
384 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
385 {
386 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
387 struct vattr vattr;
388 int error, namelen, vfslocked;
389 struct nameidata nd;
390 struct unpcb *unp;
391 struct vnode *vp;
392 struct mount *mp;
393 char *buf;
394
395 unp = sotounpcb(so);
396 KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
397
398 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
399 if (namelen <= 0)
400 return (EINVAL);
401
402 /*
403 * We don't allow simultaneous bind() calls on a single UNIX domain
404 * socket, so flag in-progress operations, and return an error if an
405 * operation is already in progress.
406 *
407 * Historically, we have not allowed a socket to be rebound, so this
408 * also returns an error. Not allowing re-binding simplifies the
409 * implementation and avoids a great many possible failure modes.
410 */
411 UNP_PCB_LOCK(unp);
412 if (unp->unp_vnode != NULL) {
413 UNP_PCB_UNLOCK(unp);
414 return (EINVAL);
415 }
416 if (unp->unp_flags & UNP_BINDING) {
417 UNP_PCB_UNLOCK(unp);
418 return (EALREADY);
419 }
420 unp->unp_flags |= UNP_BINDING;
421 UNP_PCB_UNLOCK(unp);
422
423 buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
424 strlcpy(buf, soun->sun_path, namelen + 1);
425
426 restart:
427 vfslocked = 0;
428 NDINIT(&nd, CREATE, MPSAFE | NOFOLLOW | LOCKPARENT | SAVENAME,
429 UIO_SYSSPACE, buf, td);
430 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
431 error = namei(&nd);
432 if (error)
433 goto error;
434 vp = nd.ni_vp;
435 vfslocked = NDHASGIANT(&nd);
436 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
437 NDFREE(&nd, NDF_ONLY_PNBUF);
438 if (nd.ni_dvp == vp)
439 vrele(nd.ni_dvp);
440 else
441 vput(nd.ni_dvp);
442 if (vp != NULL) {
443 vrele(vp);
444 error = EADDRINUSE;
445 goto error;
446 }
447 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
448 if (error)
449 goto error;
450 VFS_UNLOCK_GIANT(vfslocked);
451 goto restart;
452 }
453 VATTR_NULL(&vattr);
454 vattr.va_type = VSOCK;
455 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
456 #ifdef MAC
457 error = mac_check_vnode_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
458 &vattr);
459 #endif
460 if (error == 0) {
461 VOP_LEASE(nd.ni_dvp, td, td->td_ucred, LEASE_WRITE);
462 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
463 }
464 NDFREE(&nd, NDF_ONLY_PNBUF);
465 vput(nd.ni_dvp);
466 if (error) {
467 vn_finished_write(mp);
468 goto error;
469 }
470 vp = nd.ni_vp;
471 ASSERT_VOP_ELOCKED(vp, "uipc_bind");
472 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
473
474 UNP_GLOBAL_WLOCK();
475 UNP_PCB_LOCK(unp);
476 vp->v_socket = unp->unp_socket;
477 unp->unp_vnode = vp;
478 unp->unp_addr = soun;
479 unp->unp_flags &= ~UNP_BINDING;
480 UNP_PCB_UNLOCK(unp);
481 UNP_GLOBAL_WUNLOCK();
482 VOP_UNLOCK(vp, 0, td);
483 vn_finished_write(mp);
484 VFS_UNLOCK_GIANT(vfslocked);
485 free(buf, M_TEMP);
486 return (0);
487
488 error:
489 VFS_UNLOCK_GIANT(vfslocked);
490 UNP_PCB_LOCK(unp);
491 unp->unp_flags &= ~UNP_BINDING;
492 UNP_PCB_UNLOCK(unp);
493 free(buf, M_TEMP);
494 return (error);
495 }
496
497 static int
498 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
499 {
500 int error;
501
502 KASSERT(td == curthread, ("uipc_connect: td != curthread"));
503 UNP_GLOBAL_WLOCK();
504 error = unp_connect(so, nam, td);
505 UNP_GLOBAL_WUNLOCK();
506 return (error);
507 }
508
509 static void
510 uipc_close(struct socket *so)
511 {
512 struct unpcb *unp, *unp2;
513
514 unp = sotounpcb(so);
515 KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
516
517 UNP_GLOBAL_WLOCK();
518 UNP_PCB_LOCK(unp);
519 unp2 = unp->unp_conn;
520 if (unp2 != NULL) {
521 UNP_PCB_LOCK(unp2);
522 unp_disconnect(unp, unp2);
523 UNP_PCB_UNLOCK(unp2);
524 }
525 UNP_PCB_UNLOCK(unp);
526 UNP_GLOBAL_WUNLOCK();
527 }
528
529 static int
530 uipc_connect2(struct socket *so1, struct socket *so2)
531 {
532 struct unpcb *unp, *unp2;
533 int error;
534
535 UNP_GLOBAL_WLOCK();
536 unp = so1->so_pcb;
537 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
538 UNP_PCB_LOCK(unp);
539 unp2 = so2->so_pcb;
540 KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
541 UNP_PCB_LOCK(unp2);
542 error = unp_connect2(so1, so2, PRU_CONNECT2);
543 UNP_PCB_UNLOCK(unp2);
544 UNP_PCB_UNLOCK(unp);
545 UNP_GLOBAL_WUNLOCK();
546 return (error);
547 }
548
549 static void
550 uipc_detach(struct socket *so)
551 {
552 struct unpcb *unp, *unp2;
553 struct sockaddr_un *saved_unp_addr;
554 struct vnode *vp;
555 int freeunp, local_unp_rights;
556
557 unp = sotounpcb(so);
558 KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
559
560 UNP_GLOBAL_WLOCK();
561 UNP_PCB_LOCK(unp);
562
563 LIST_REMOVE(unp, unp_link);
564 unp->unp_gencnt = ++unp_gencnt;
565 --unp_count;
566
567 /*
568 * XXXRW: Should assert vp->v_socket == so.
569 */
570 if ((vp = unp->unp_vnode) != NULL) {
571 unp->unp_vnode->v_socket = NULL;
572 unp->unp_vnode = NULL;
573 }
574 unp2 = unp->unp_conn;
575 if (unp2 != NULL) {
576 UNP_PCB_LOCK(unp2);
577 unp_disconnect(unp, unp2);
578 UNP_PCB_UNLOCK(unp2);
579 }
580
581 /*
582 * We hold the global lock exclusively, so it's OK to acquire
583 * multiple pcb locks at a time.
584 */
585 while (!LIST_EMPTY(&unp->unp_refs)) {
586 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
587
588 UNP_PCB_LOCK(ref);
589 unp_drop(ref, ECONNRESET);
590 UNP_PCB_UNLOCK(ref);
591 }
592 local_unp_rights = unp_rights;
593 UNP_GLOBAL_WUNLOCK();
594 unp->unp_socket->so_pcb = NULL;
595 saved_unp_addr = unp->unp_addr;
596 unp->unp_addr = NULL;
597 unp->unp_refcount--;
598 freeunp = (unp->unp_refcount == 0);
599 if (saved_unp_addr != NULL)
600 FREE(saved_unp_addr, M_SONAME);
601 if (freeunp) {
602 UNP_PCB_LOCK_DESTROY(unp);
603 uma_zfree(unp_zone, unp);
604 } else
605 UNP_PCB_UNLOCK(unp);
606 if (vp) {
607 int vfslocked;
608
609 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
610 vrele(vp);
611 VFS_UNLOCK_GIANT(vfslocked);
612 }
613 if (local_unp_rights)
614 taskqueue_enqueue(taskqueue_thread, &unp_gc_task);
615 }
616
617 static int
618 uipc_disconnect(struct socket *so)
619 {
620 struct unpcb *unp, *unp2;
621
622 unp = sotounpcb(so);
623 KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
624
625 UNP_GLOBAL_WLOCK();
626 UNP_PCB_LOCK(unp);
627 unp2 = unp->unp_conn;
628 if (unp2 != NULL) {
629 UNP_PCB_LOCK(unp2);
630 unp_disconnect(unp, unp2);
631 UNP_PCB_UNLOCK(unp2);
632 }
633 UNP_PCB_UNLOCK(unp);
634 UNP_GLOBAL_WUNLOCK();
635 return (0);
636 }
637
638 static int
639 uipc_listen(struct socket *so, int backlog, struct thread *td)
640 {
641 struct unpcb *unp;
642 int error;
643
644 unp = sotounpcb(so);
645 KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
646
647 UNP_PCB_LOCK(unp);
648 if (unp->unp_vnode == NULL) {
649 UNP_PCB_UNLOCK(unp);
650 return (EINVAL);
651 }
652
653 SOCK_LOCK(so);
654 error = solisten_proto_check(so);
655 if (error == 0) {
656 cru2x(td->td_ucred, &unp->unp_peercred);
657 unp->unp_flags |= UNP_HAVEPCCACHED;
658 solisten_proto(so, backlog);
659 }
660 SOCK_UNLOCK(so);
661 UNP_PCB_UNLOCK(unp);
662 return (error);
663 }
664
665 static int
666 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
667 {
668 struct unpcb *unp, *unp2;
669 const struct sockaddr *sa;
670
671 unp = sotounpcb(so);
672 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
673
674 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
675 UNP_PCB_LOCK(unp);
676 /*
677 * XXX: It seems that this test always fails even when connection is
678 * established. So, this else clause is added as workaround to
679 * return PF_LOCAL sockaddr.
680 */
681 unp2 = unp->unp_conn;
682 if (unp2 != NULL) {
683 UNP_PCB_LOCK(unp2);
684 if (unp2->unp_addr != NULL)
685 sa = (struct sockaddr *) unp->unp_conn->unp_addr;
686 else
687 sa = &sun_noname;
688 bcopy(sa, *nam, sa->sa_len);
689 UNP_PCB_UNLOCK(unp2);
690 } else {
691 sa = &sun_noname;
692 bcopy(sa, *nam, sa->sa_len);
693 }
694 UNP_PCB_UNLOCK(unp);
695 return (0);
696 }
697
698 static int
699 uipc_rcvd(struct socket *so, int flags)
700 {
701 struct unpcb *unp, *unp2;
702 struct socket *so2;
703 u_int mbcnt, sbcc;
704 u_long newhiwat;
705
706 unp = sotounpcb(so);
707 KASSERT(unp != NULL, ("uipc_rcvd: unp == NULL"));
708
709 if (so->so_type == SOCK_DGRAM)
710 panic("uipc_rcvd DGRAM?");
711
712 if (so->so_type != SOCK_STREAM)
713 panic("uipc_rcvd unknown socktype");
714
715 /*
716 * Adjust backpressure on sender and wakeup any waiting to write.
717 *
718 * The unp lock is acquired to maintain the validity of the unp_conn
719 * pointer; no lock on unp2 is required as unp2->unp_socket will be
720 * static as long as we don't permit unp2 to disconnect from unp,
721 * which is prevented by the lock on unp. We cache values from
722 * so_rcv to avoid holding the so_rcv lock over the entire
723 * transaction on the remote so_snd.
724 */
725 SOCKBUF_LOCK(&so->so_rcv);
726 mbcnt = so->so_rcv.sb_mbcnt;
727 sbcc = so->so_rcv.sb_cc;
728 SOCKBUF_UNLOCK(&so->so_rcv);
729 UNP_PCB_LOCK(unp);
730 unp2 = unp->unp_conn;
731 if (unp2 == NULL) {
732 UNP_PCB_UNLOCK(unp);
733 return (0);
734 }
735 so2 = unp2->unp_socket;
736 SOCKBUF_LOCK(&so2->so_snd);
737 so2->so_snd.sb_mbmax += unp->unp_mbcnt - mbcnt;
738 newhiwat = so2->so_snd.sb_hiwat + unp->unp_cc - sbcc;
739 (void)chgsbsize(so2->so_cred->cr_uidinfo, &so2->so_snd.sb_hiwat,
740 newhiwat, RLIM_INFINITY);
741 sowwakeup_locked(so2);
742 unp->unp_mbcnt = mbcnt;
743 unp->unp_cc = sbcc;
744 UNP_PCB_UNLOCK(unp);
745 return (0);
746 }
747
748 static int
749 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
750 struct mbuf *control, struct thread *td)
751 {
752 struct unpcb *unp, *unp2;
753 struct socket *so2;
754 u_int mbcnt, sbcc;
755 u_long newhiwat;
756 int error = 0;
757
758 unp = sotounpcb(so);
759 KASSERT(unp != NULL, ("uipc_send: unp == NULL"));
760
761 if (flags & PRUS_OOB) {
762 error = EOPNOTSUPP;
763 goto release;
764 }
765 if (control != NULL && (error = unp_internalize(&control, td)))
766 goto release;
767 if ((nam != NULL) || (flags & PRUS_EOF))
768 UNP_GLOBAL_WLOCK();
769 else
770 UNP_GLOBAL_RLOCK();
771 switch (so->so_type) {
772 case SOCK_DGRAM:
773 {
774 const struct sockaddr *from;
775
776 unp2 = unp->unp_conn;
777 if (nam != NULL) {
778 UNP_GLOBAL_WLOCK_ASSERT();
779 if (unp2 != NULL) {
780 error = EISCONN;
781 break;
782 }
783 error = unp_connect(so, nam, td);
784 if (error)
785 break;
786 unp2 = unp->unp_conn;
787 }
788
789 /*
790 * Because connect() and send() are non-atomic in a sendto()
791 * with a target address, it's possible that the socket will
792 * have disconnected before the send() can run. In that case
793 * return the slightly counter-intuitive but otherwise
794 * correct error that the socket is not connected.
795 */
796 if (unp2 == NULL) {
797 error = ENOTCONN;
798 break;
799 }
800 /* Lockless read. */
801 if (unp2->unp_flags & UNP_WANTCRED)
802 control = unp_addsockcred(td, control);
803 UNP_PCB_LOCK(unp);
804 if (unp->unp_addr != NULL)
805 from = (struct sockaddr *)unp->unp_addr;
806 else
807 from = &sun_noname;
808 so2 = unp2->unp_socket;
809 SOCKBUF_LOCK(&so2->so_rcv);
810 if (sbappendaddr_locked(&so2->so_rcv, from, m, control)) {
811 sorwakeup_locked(so2);
812 m = NULL;
813 control = NULL;
814 } else {
815 SOCKBUF_UNLOCK(&so2->so_rcv);
816 error = ENOBUFS;
817 }
818 if (nam != NULL) {
819 UNP_GLOBAL_WLOCK_ASSERT();
820 UNP_PCB_LOCK(unp2);
821 unp_disconnect(unp, unp2);
822 UNP_PCB_UNLOCK(unp2);
823 }
824 UNP_PCB_UNLOCK(unp);
825 break;
826 }
827
828 case SOCK_STREAM:
829 if ((so->so_state & SS_ISCONNECTED) == 0) {
830 if (nam != NULL) {
831 UNP_GLOBAL_WLOCK_ASSERT();
832 error = unp_connect(so, nam, td);
833 if (error)
834 break; /* XXX */
835 } else {
836 error = ENOTCONN;
837 break;
838 }
839 }
840
841 /* Lockless read. */
842 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
843 error = EPIPE;
844 break;
845 }
846
847 /*
848 * Because connect() and send() are non-atomic in a sendto()
849 * with a target address, it's possible that the socket will
850 * have disconnected before the send() can run. In that case
851 * return the slightly counter-intuitive but otherwise
852 * correct error that the socket is not connected.
853 *
854 * Locking here must be done carefully: the global lock
855 * prevents interconnections between unpcbs from changing, so
856 * we can traverse from unp to unp2 without acquiring unp's
857 * lock. Socket buffer locks follow unpcb locks, so we can
858 * acquire both remote and lock socket buffer locks.
859 */
860 unp2 = unp->unp_conn;
861 if (unp2 == NULL) {
862 error = ENOTCONN;
863 break;
864 }
865 so2 = unp2->unp_socket;
866 UNP_PCB_LOCK(unp2);
867 SOCKBUF_LOCK(&so2->so_rcv);
868 if (unp2->unp_flags & UNP_WANTCRED) {
869 /*
870 * Credentials are passed only once on SOCK_STREAM.
871 */
872 unp2->unp_flags &= ~UNP_WANTCRED;
873 control = unp_addsockcred(td, control);
874 }
875 /*
876 * Send to paired receive port, and then reduce send buffer
877 * hiwater marks to maintain backpressure. Wake up readers.
878 */
879 if (control != NULL) {
880 if (sbappendcontrol_locked(&so2->so_rcv, m, control))
881 control = NULL;
882 } else
883 sbappend_locked(&so2->so_rcv, m);
884 mbcnt = so2->so_rcv.sb_mbcnt - unp2->unp_mbcnt;
885 unp2->unp_mbcnt = so2->so_rcv.sb_mbcnt;
886 sbcc = so2->so_rcv.sb_cc;
887 sorwakeup_locked(so2);
888
889 SOCKBUF_LOCK(&so->so_snd);
890 newhiwat = so->so_snd.sb_hiwat - (sbcc - unp2->unp_cc);
891 (void)chgsbsize(so->so_cred->cr_uidinfo, &so->so_snd.sb_hiwat,
892 newhiwat, RLIM_INFINITY);
893 so->so_snd.sb_mbmax -= mbcnt;
894 SOCKBUF_UNLOCK(&so->so_snd);
895 unp2->unp_cc = sbcc;
896 UNP_PCB_UNLOCK(unp2);
897 m = NULL;
898 break;
899
900 default:
901 panic("uipc_send unknown socktype");
902 }
903
904 /*
905 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
906 */
907 if (flags & PRUS_EOF) {
908 UNP_PCB_LOCK(unp);
909 socantsendmore(so);
910 unp_shutdown(unp);
911 UNP_PCB_UNLOCK(unp);
912 }
913
914 if ((nam != NULL) || (flags & PRUS_EOF))
915 UNP_GLOBAL_WUNLOCK();
916 else
917 UNP_GLOBAL_RUNLOCK();
918
919 if (control != NULL && error != 0)
920 unp_dispose(control);
921
922 release:
923 if (control != NULL)
924 m_freem(control);
925 if (m != NULL)
926 m_freem(m);
927 return (error);
928 }
929
930 static int
931 uipc_sense(struct socket *so, struct stat *sb)
932 {
933 struct unpcb *unp, *unp2;
934 struct socket *so2;
935
936 unp = sotounpcb(so);
937 KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
938
939 sb->st_blksize = so->so_snd.sb_hiwat;
940 UNP_GLOBAL_RLOCK();
941 UNP_PCB_LOCK(unp);
942 unp2 = unp->unp_conn;
943 if (so->so_type == SOCK_STREAM && unp2 != NULL) {
944 so2 = unp2->unp_socket;
945 sb->st_blksize += so2->so_rcv.sb_cc;
946 }
947 sb->st_dev = NODEV;
948 if (unp->unp_ino == 0)
949 unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
950 sb->st_ino = unp->unp_ino;
951 UNP_PCB_UNLOCK(unp);
952 UNP_GLOBAL_RUNLOCK();
953 return (0);
954 }
955
956 static int
957 uipc_shutdown(struct socket *so)
958 {
959 struct unpcb *unp;
960
961 unp = sotounpcb(so);
962 KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
963
964 UNP_GLOBAL_WLOCK();
965 UNP_PCB_LOCK(unp);
966 socantsendmore(so);
967 unp_shutdown(unp);
968 UNP_PCB_UNLOCK(unp);
969 UNP_GLOBAL_WUNLOCK();
970 return (0);
971 }
972
973 static int
974 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
975 {
976 struct unpcb *unp;
977 const struct sockaddr *sa;
978
979 unp = sotounpcb(so);
980 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
981
982 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
983 UNP_PCB_LOCK(unp);
984 if (unp->unp_addr != NULL)
985 sa = (struct sockaddr *) unp->unp_addr;
986 else
987 sa = &sun_noname;
988 bcopy(sa, *nam, sa->sa_len);
989 UNP_PCB_UNLOCK(unp);
990 return (0);
991 }
992
993 static struct pr_usrreqs uipc_usrreqs = {
994 .pru_abort = uipc_abort,
995 .pru_accept = uipc_accept,
996 .pru_attach = uipc_attach,
997 .pru_bind = uipc_bind,
998 .pru_connect = uipc_connect,
999 .pru_connect2 = uipc_connect2,
1000 .pru_detach = uipc_detach,
1001 .pru_disconnect = uipc_disconnect,
1002 .pru_listen = uipc_listen,
1003 .pru_peeraddr = uipc_peeraddr,
1004 .pru_rcvd = uipc_rcvd,
1005 .pru_send = uipc_send,
1006 .pru_sense = uipc_sense,
1007 .pru_shutdown = uipc_shutdown,
1008 .pru_sockaddr = uipc_sockaddr,
1009 .pru_close = uipc_close,
1010 };
1011
1012 static int
1013 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1014 {
1015 struct unpcb *unp;
1016 struct xucred xu;
1017 int error, optval;
1018
1019 if (sopt->sopt_level != 0)
1020 return (EINVAL);
1021
1022 unp = sotounpcb(so);
1023 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1024 error = 0;
1025 switch (sopt->sopt_dir) {
1026 case SOPT_GET:
1027 switch (sopt->sopt_name) {
1028 case LOCAL_PEERCRED:
1029 UNP_PCB_LOCK(unp);
1030 if (unp->unp_flags & UNP_HAVEPC)
1031 xu = unp->unp_peercred;
1032 else {
1033 if (so->so_type == SOCK_STREAM)
1034 error = ENOTCONN;
1035 else
1036 error = EINVAL;
1037 }
1038 UNP_PCB_UNLOCK(unp);
1039 if (error == 0)
1040 error = sooptcopyout(sopt, &xu, sizeof(xu));
1041 break;
1042
1043 case LOCAL_CREDS:
1044 /* Unlocked read. */
1045 optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
1046 error = sooptcopyout(sopt, &optval, sizeof(optval));
1047 break;
1048
1049 case LOCAL_CONNWAIT:
1050 /* Unlocked read. */
1051 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1052 error = sooptcopyout(sopt, &optval, sizeof(optval));
1053 break;
1054
1055 default:
1056 error = EOPNOTSUPP;
1057 break;
1058 }
1059 break;
1060
1061 case SOPT_SET:
1062 switch (sopt->sopt_name) {
1063 case LOCAL_CREDS:
1064 case LOCAL_CONNWAIT:
1065 error = sooptcopyin(sopt, &optval, sizeof(optval),
1066 sizeof(optval));
1067 if (error)
1068 break;
1069
1070 #define OPTSET(bit) do { \
1071 UNP_PCB_LOCK(unp); \
1072 if (optval) \
1073 unp->unp_flags |= bit; \
1074 else \
1075 unp->unp_flags &= ~bit; \
1076 UNP_PCB_UNLOCK(unp); \
1077 } while (0)
1078
1079 switch (sopt->sopt_name) {
1080 case LOCAL_CREDS:
1081 OPTSET(UNP_WANTCRED);
1082 break;
1083
1084 case LOCAL_CONNWAIT:
1085 OPTSET(UNP_CONNWAIT);
1086 break;
1087
1088 default:
1089 break;
1090 }
1091 break;
1092 #undef OPTSET
1093 default:
1094 error = ENOPROTOOPT;
1095 break;
1096 }
1097 break;
1098
1099 default:
1100 error = EOPNOTSUPP;
1101 break;
1102 }
1103 return (error);
1104 }
1105
1106 static int
1107 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1108 {
1109 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
1110 struct vnode *vp;
1111 struct socket *so2, *so3;
1112 struct unpcb *unp, *unp2, *unp3;
1113 int error, len, vfslocked;
1114 struct nameidata nd;
1115 char buf[SOCK_MAXADDRLEN];
1116 struct sockaddr *sa;
1117
1118 UNP_GLOBAL_WLOCK_ASSERT();
1119
1120 unp = sotounpcb(so);
1121 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1122
1123 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1124 if (len <= 0)
1125 return (EINVAL);
1126 strlcpy(buf, soun->sun_path, len + 1);
1127
1128 UNP_PCB_LOCK(unp);
1129 if (unp->unp_flags & UNP_CONNECTING) {
1130 UNP_PCB_UNLOCK(unp);
1131 return (EALREADY);
1132 }
1133 UNP_GLOBAL_WUNLOCK();
1134 unp->unp_flags |= UNP_CONNECTING;
1135 UNP_PCB_UNLOCK(unp);
1136
1137 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1138 NDINIT(&nd, LOOKUP, MPSAFE | FOLLOW | LOCKLEAF, UIO_SYSSPACE, buf,
1139 td);
1140 error = namei(&nd);
1141 if (error)
1142 vp = NULL;
1143 else
1144 vp = nd.ni_vp;
1145 ASSERT_VOP_LOCKED(vp, "unp_connect");
1146 vfslocked = NDHASGIANT(&nd);
1147 NDFREE(&nd, NDF_ONLY_PNBUF);
1148 if (error)
1149 goto bad;
1150
1151 if (vp->v_type != VSOCK) {
1152 error = ENOTSOCK;
1153 goto bad;
1154 }
1155 #ifdef MAC
1156 error = mac_check_vnode_open(td->td_ucred, vp, VWRITE | VREAD);
1157 if (error)
1158 goto bad;
1159 #endif
1160 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1161 if (error)
1162 goto bad;
1163 VFS_UNLOCK_GIANT(vfslocked);
1164
1165 unp = sotounpcb(so);
1166 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1167
1168 /*
1169 * Lock global lock for two reasons: make sure v_socket is stable,
1170 * and to protect simultaneous locking of multiple pcbs.
1171 */
1172 UNP_GLOBAL_WLOCK();
1173 so2 = vp->v_socket;
1174 if (so2 == NULL) {
1175 error = ECONNREFUSED;
1176 goto bad2;
1177 }
1178 if (so->so_type != so2->so_type) {
1179 error = EPROTOTYPE;
1180 goto bad2;
1181 }
1182 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
1183 if (so2->so_options & SO_ACCEPTCONN) {
1184 /*
1185 * We can't drop the global lock here or 'so2' may
1186 * become invalid. As a result, we need to handle
1187 * possibly lock recursion in uipc_attach.
1188 */
1189 so3 = sonewconn(so2, 0);
1190 } else
1191 so3 = NULL;
1192 if (so3 == NULL) {
1193 error = ECONNREFUSED;
1194 goto bad2;
1195 }
1196 unp = sotounpcb(so);
1197 unp2 = sotounpcb(so2);
1198 unp3 = sotounpcb(so3);
1199 UNP_PCB_LOCK(unp);
1200 UNP_PCB_LOCK(unp2);
1201 UNP_PCB_LOCK(unp3);
1202 if (unp2->unp_addr != NULL) {
1203 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1204 unp3->unp_addr = (struct sockaddr_un *) sa;
1205 sa = NULL;
1206 }
1207 /*
1208 * unp_peercred management:
1209 *
1210 * The connecter's (client's) credentials are copied from its
1211 * process structure at the time of connect() (which is now).
1212 */
1213 cru2x(td->td_ucred, &unp3->unp_peercred);
1214 unp3->unp_flags |= UNP_HAVEPC;
1215 /*
1216 * The receiver's (server's) credentials are copied from the
1217 * unp_peercred member of socket on which the former called
1218 * listen(); uipc_listen() cached that process's credentials
1219 * at that time so we can use them now.
1220 */
1221 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
1222 ("unp_connect: listener without cached peercred"));
1223 memcpy(&unp->unp_peercred, &unp2->unp_peercred,
1224 sizeof(unp->unp_peercred));
1225 unp->unp_flags |= UNP_HAVEPC;
1226 if (unp2->unp_flags & UNP_WANTCRED)
1227 unp3->unp_flags |= UNP_WANTCRED;
1228 UNP_PCB_UNLOCK(unp3);
1229 UNP_PCB_UNLOCK(unp2);
1230 UNP_PCB_UNLOCK(unp);
1231 #ifdef MAC
1232 SOCK_LOCK(so);
1233 mac_set_socket_peer_from_socket(so, so3);
1234 mac_set_socket_peer_from_socket(so3, so);
1235 SOCK_UNLOCK(so);
1236 #endif
1237
1238 so2 = so3;
1239 }
1240 unp = sotounpcb(so);
1241 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1242 unp2 = sotounpcb(so2);
1243 KASSERT(unp2 != NULL, ("unp_connect: unp2 == NULL"));
1244 UNP_PCB_LOCK(unp);
1245 UNP_PCB_LOCK(unp2);
1246 error = unp_connect2(so, so2, PRU_CONNECT);
1247 UNP_PCB_UNLOCK(unp2);
1248 UNP_PCB_UNLOCK(unp);
1249 bad2:
1250 UNP_GLOBAL_WUNLOCK();
1251 if (vfslocked)
1252 /*
1253 * Giant has been previously acquired. This means filesystem
1254 * isn't MPSAFE. Do it once again.
1255 */
1256 mtx_lock(&Giant);
1257 bad:
1258 if (vp != NULL)
1259 vput(vp);
1260 VFS_UNLOCK_GIANT(vfslocked);
1261 free(sa, M_SONAME);
1262 UNP_GLOBAL_WLOCK();
1263 UNP_PCB_LOCK(unp);
1264 unp->unp_flags &= ~UNP_CONNECTING;
1265 UNP_PCB_UNLOCK(unp);
1266 return (error);
1267 }
1268
1269 static int
1270 unp_connect2(struct socket *so, struct socket *so2, int req)
1271 {
1272 struct unpcb *unp;
1273 struct unpcb *unp2;
1274
1275 unp = sotounpcb(so);
1276 KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1277 unp2 = sotounpcb(so2);
1278 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1279
1280 UNP_GLOBAL_WLOCK_ASSERT();
1281 UNP_PCB_LOCK_ASSERT(unp);
1282 UNP_PCB_LOCK_ASSERT(unp2);
1283
1284 if (so2->so_type != so->so_type)
1285 return (EPROTOTYPE);
1286 unp->unp_conn = unp2;
1287
1288 switch (so->so_type) {
1289 case SOCK_DGRAM:
1290 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1291 soisconnected(so);
1292 break;
1293
1294 case SOCK_STREAM:
1295 unp2->unp_conn = unp;
1296 if (req == PRU_CONNECT &&
1297 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1298 soisconnecting(so);
1299 else
1300 soisconnected(so);
1301 soisconnected(so2);
1302 break;
1303
1304 default:
1305 panic("unp_connect2");
1306 }
1307 return (0);
1308 }
1309
1310 static void
1311 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1312 {
1313 struct socket *so;
1314
1315 KASSERT(unp2 != NULL, ("unp_disconnect: unp2 == NULL"));
1316
1317 UNP_GLOBAL_WLOCK_ASSERT();
1318 UNP_PCB_LOCK_ASSERT(unp);
1319 UNP_PCB_LOCK_ASSERT(unp2);
1320
1321 unp->unp_conn = NULL;
1322 switch (unp->unp_socket->so_type) {
1323 case SOCK_DGRAM:
1324 LIST_REMOVE(unp, unp_reflink);
1325 so = unp->unp_socket;
1326 SOCK_LOCK(so);
1327 so->so_state &= ~SS_ISCONNECTED;
1328 SOCK_UNLOCK(so);
1329 break;
1330
1331 case SOCK_STREAM:
1332 soisdisconnected(unp->unp_socket);
1333 unp2->unp_conn = NULL;
1334 soisdisconnected(unp2->unp_socket);
1335 break;
1336 }
1337 }
1338
1339 /*
1340 * unp_pcblist() walks the global list of struct unpcb's to generate a
1341 * pointer list, bumping the refcount on each unpcb. It then copies them out
1342 * sequentially, validating the generation number on each to see if it has
1343 * been detached. All of this is necessary because copyout() may sleep on
1344 * disk I/O.
1345 */
1346 static int
1347 unp_pcblist(SYSCTL_HANDLER_ARGS)
1348 {
1349 int error, i, n;
1350 int freeunp;
1351 struct unpcb *unp, **unp_list;
1352 unp_gen_t gencnt;
1353 struct xunpgen *xug;
1354 struct unp_head *head;
1355 struct xunpcb *xu;
1356
1357 head = ((intptr_t)arg1 == SOCK_DGRAM ? &unp_dhead : &unp_shead);
1358
1359 /*
1360 * The process of preparing the PCB list is too time-consuming and
1361 * resource-intensive to repeat twice on every request.
1362 */
1363 if (req->oldptr == NULL) {
1364 n = unp_count;
1365 req->oldidx = 2 * (sizeof *xug)
1366 + (n + n/8) * sizeof(struct xunpcb);
1367 return (0);
1368 }
1369
1370 if (req->newptr != NULL)
1371 return (EPERM);
1372
1373 /*
1374 * OK, now we're committed to doing something.
1375 */
1376 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
1377 UNP_GLOBAL_RLOCK();
1378 gencnt = unp_gencnt;
1379 n = unp_count;
1380 UNP_GLOBAL_RUNLOCK();
1381
1382 xug->xug_len = sizeof *xug;
1383 xug->xug_count = n;
1384 xug->xug_gen = gencnt;
1385 xug->xug_sogen = so_gencnt;
1386 error = SYSCTL_OUT(req, xug, sizeof *xug);
1387 if (error) {
1388 free(xug, M_TEMP);
1389 return (error);
1390 }
1391
1392 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1393
1394 UNP_GLOBAL_RLOCK();
1395 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1396 unp = LIST_NEXT(unp, unp_link)) {
1397 UNP_PCB_LOCK(unp);
1398 if (unp->unp_gencnt <= gencnt) {
1399 if (cr_cansee(req->td->td_ucred,
1400 unp->unp_socket->so_cred)) {
1401 UNP_PCB_UNLOCK(unp);
1402 continue;
1403 }
1404 unp_list[i++] = unp;
1405 unp->unp_refcount++;
1406 }
1407 UNP_PCB_UNLOCK(unp);
1408 }
1409 UNP_GLOBAL_RUNLOCK();
1410 n = i; /* In case we lost some during malloc. */
1411
1412 error = 0;
1413 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1414 for (i = 0; i < n; i++) {
1415 unp = unp_list[i];
1416 UNP_PCB_LOCK(unp);
1417 unp->unp_refcount--;
1418 if (unp->unp_refcount != 0 && unp->unp_gencnt <= gencnt) {
1419 xu->xu_len = sizeof *xu;
1420 xu->xu_unpp = unp;
1421 /*
1422 * XXX - need more locking here to protect against
1423 * connect/disconnect races for SMP.
1424 */
1425 if (unp->unp_addr != NULL)
1426 bcopy(unp->unp_addr, &xu->xu_addr,
1427 unp->unp_addr->sun_len);
1428 if (unp->unp_conn != NULL &&
1429 unp->unp_conn->unp_addr != NULL)
1430 bcopy(unp->unp_conn->unp_addr,
1431 &xu->xu_caddr,
1432 unp->unp_conn->unp_addr->sun_len);
1433 bcopy(unp, &xu->xu_unp, sizeof *unp);
1434 sotoxsocket(unp->unp_socket, &xu->xu_socket);
1435 UNP_PCB_UNLOCK(unp);
1436 error = SYSCTL_OUT(req, xu, sizeof *xu);
1437 } else {
1438 freeunp = (unp->unp_refcount == 0);
1439 UNP_PCB_UNLOCK(unp);
1440 if (freeunp) {
1441 UNP_PCB_LOCK_DESTROY(unp);
1442 uma_zfree(unp_zone, unp);
1443 }
1444 }
1445 }
1446 free(xu, M_TEMP);
1447 if (!error) {
1448 /*
1449 * Give the user an updated idea of our state. If the
1450 * generation differs from what we told her before, she knows
1451 * that something happened while we were processing this
1452 * request, and it might be necessary to retry.
1453 */
1454 xug->xug_gen = unp_gencnt;
1455 xug->xug_sogen = so_gencnt;
1456 xug->xug_count = unp_count;
1457 error = SYSCTL_OUT(req, xug, sizeof *xug);
1458 }
1459 free(unp_list, M_TEMP);
1460 free(xug, M_TEMP);
1461 return (error);
1462 }
1463
1464 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD,
1465 (caddr_t)(long)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1466 "List of active local datagram sockets");
1467 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD,
1468 (caddr_t)(long)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1469 "List of active local stream sockets");
1470
1471 static void
1472 unp_shutdown(struct unpcb *unp)
1473 {
1474 struct unpcb *unp2;
1475 struct socket *so;
1476
1477 UNP_GLOBAL_WLOCK_ASSERT();
1478 UNP_PCB_LOCK_ASSERT(unp);
1479
1480 unp2 = unp->unp_conn;
1481 if (unp->unp_socket->so_type == SOCK_STREAM && unp2 != NULL) {
1482 so = unp2->unp_socket;
1483 if (so != NULL)
1484 socantrcvmore(so);
1485 }
1486 }
1487
1488 static void
1489 unp_drop(struct unpcb *unp, int errno)
1490 {
1491 struct socket *so = unp->unp_socket;
1492 struct unpcb *unp2;
1493
1494 UNP_GLOBAL_WLOCK_ASSERT();
1495 UNP_PCB_LOCK_ASSERT(unp);
1496
1497 so->so_error = errno;
1498 unp2 = unp->unp_conn;
1499 if (unp2 == NULL)
1500 return;
1501 UNP_PCB_LOCK(unp2);
1502 unp_disconnect(unp, unp2);
1503 UNP_PCB_UNLOCK(unp2);
1504 }
1505
1506 static void
1507 unp_freerights(struct file **rp, int fdcount)
1508 {
1509 int i;
1510 struct file *fp;
1511
1512 for (i = 0; i < fdcount; i++) {
1513 fp = *rp;
1514 *rp++ = NULL;
1515 unp_discard(fp);
1516 }
1517 }
1518
1519 static int
1520 unp_externalize(struct mbuf *control, struct mbuf **controlp)
1521 {
1522 struct thread *td = curthread; /* XXX */
1523 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1524 int i;
1525 int *fdp;
1526 struct file **rp;
1527 struct file *fp;
1528 void *data;
1529 socklen_t clen = control->m_len, datalen;
1530 int error, newfds;
1531 int f;
1532 u_int newlen;
1533
1534 UNP_GLOBAL_UNLOCK_ASSERT();
1535
1536 error = 0;
1537 if (controlp != NULL) /* controlp == NULL => free control messages */
1538 *controlp = NULL;
1539 while (cm != NULL) {
1540 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1541 error = EINVAL;
1542 break;
1543 }
1544 data = CMSG_DATA(cm);
1545 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1546 if (cm->cmsg_level == SOL_SOCKET
1547 && cm->cmsg_type == SCM_RIGHTS) {
1548 newfds = datalen / sizeof(struct file *);
1549 rp = data;
1550
1551 /* If we're not outputting the descriptors free them. */
1552 if (error || controlp == NULL) {
1553 unp_freerights(rp, newfds);
1554 goto next;
1555 }
1556 FILEDESC_XLOCK(td->td_proc->p_fd);
1557 /* if the new FD's will not fit free them. */
1558 if (!fdavail(td, newfds)) {
1559 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1560 error = EMSGSIZE;
1561 unp_freerights(rp, newfds);
1562 goto next;
1563 }
1564
1565 /*
1566 * Now change each pointer to an fd in the global
1567 * table to an integer that is the index to the local
1568 * fd table entry that we set up to point to the
1569 * global one we are transferring.
1570 */
1571 newlen = newfds * sizeof(int);
1572 *controlp = sbcreatecontrol(NULL, newlen,
1573 SCM_RIGHTS, SOL_SOCKET);
1574 if (*controlp == NULL) {
1575 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1576 error = E2BIG;
1577 unp_freerights(rp, newfds);
1578 goto next;
1579 }
1580
1581 fdp = (int *)
1582 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1583 for (i = 0; i < newfds; i++) {
1584 if (fdalloc(td, 0, &f))
1585 panic("unp_externalize fdalloc failed");
1586 fp = *rp++;
1587 td->td_proc->p_fd->fd_ofiles[f] = fp;
1588 FILE_LOCK(fp);
1589 fp->f_msgcount--;
1590 FILE_UNLOCK(fp);
1591 UNP_GLOBAL_WLOCK();
1592 unp_rights--;
1593 UNP_GLOBAL_WUNLOCK();
1594 *fdp++ = f;
1595 }
1596 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1597 } else {
1598 /* We can just copy anything else across. */
1599 if (error || controlp == NULL)
1600 goto next;
1601 *controlp = sbcreatecontrol(NULL, datalen,
1602 cm->cmsg_type, cm->cmsg_level);
1603 if (*controlp == NULL) {
1604 error = ENOBUFS;
1605 goto next;
1606 }
1607 bcopy(data,
1608 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
1609 datalen);
1610 }
1611 controlp = &(*controlp)->m_next;
1612
1613 next:
1614 if (CMSG_SPACE(datalen) < clen) {
1615 clen -= CMSG_SPACE(datalen);
1616 cm = (struct cmsghdr *)
1617 ((caddr_t)cm + CMSG_SPACE(datalen));
1618 } else {
1619 clen = 0;
1620 cm = NULL;
1621 }
1622 }
1623
1624 m_freem(control);
1625 return (error);
1626 }
1627
1628 static void
1629 unp_zone_change(void *tag)
1630 {
1631
1632 uma_zone_set_max(unp_zone, maxsockets);
1633 }
1634
1635 static void
1636 unp_init(void)
1637 {
1638
1639 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
1640 NULL, NULL, UMA_ALIGN_PTR, 0);
1641 if (unp_zone == NULL)
1642 panic("unp_init");
1643 uma_zone_set_max(unp_zone, maxsockets);
1644 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
1645 NULL, EVENTHANDLER_PRI_ANY);
1646 LIST_INIT(&unp_dhead);
1647 LIST_INIT(&unp_shead);
1648 TASK_INIT(&unp_gc_task, 0, unp_gc, NULL);
1649 UNP_GLOBAL_LOCK_INIT();
1650 }
1651
1652 static int
1653 unp_internalize(struct mbuf **controlp, struct thread *td)
1654 {
1655 struct mbuf *control = *controlp;
1656 struct proc *p = td->td_proc;
1657 struct filedesc *fdescp = p->p_fd;
1658 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1659 struct cmsgcred *cmcred;
1660 struct file **rp;
1661 struct file *fp;
1662 struct timeval *tv;
1663 int i, fd, *fdp;
1664 void *data;
1665 socklen_t clen = control->m_len, datalen;
1666 int error, oldfds;
1667 u_int newlen;
1668
1669 UNP_GLOBAL_UNLOCK_ASSERT();
1670
1671 error = 0;
1672 *controlp = NULL;
1673 while (cm != NULL) {
1674 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
1675 || cm->cmsg_len > clen) {
1676 error = EINVAL;
1677 goto out;
1678 }
1679 data = CMSG_DATA(cm);
1680 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1681
1682 switch (cm->cmsg_type) {
1683 /*
1684 * Fill in credential information.
1685 */
1686 case SCM_CREDS:
1687 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
1688 SCM_CREDS, SOL_SOCKET);
1689 if (*controlp == NULL) {
1690 error = ENOBUFS;
1691 goto out;
1692 }
1693 cmcred = (struct cmsgcred *)
1694 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1695 cmcred->cmcred_pid = p->p_pid;
1696 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
1697 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
1698 cmcred->cmcred_euid = td->td_ucred->cr_uid;
1699 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
1700 CMGROUP_MAX);
1701 for (i = 0; i < cmcred->cmcred_ngroups; i++)
1702 cmcred->cmcred_groups[i] =
1703 td->td_ucred->cr_groups[i];
1704 break;
1705
1706 case SCM_RIGHTS:
1707 oldfds = datalen / sizeof (int);
1708 /*
1709 * Check that all the FDs passed in refer to legal
1710 * files. If not, reject the entire operation.
1711 */
1712 fdp = data;
1713 FILEDESC_SLOCK(fdescp);
1714 for (i = 0; i < oldfds; i++) {
1715 fd = *fdp++;
1716 if ((unsigned)fd >= fdescp->fd_nfiles ||
1717 fdescp->fd_ofiles[fd] == NULL) {
1718 FILEDESC_SUNLOCK(fdescp);
1719 error = EBADF;
1720 goto out;
1721 }
1722 fp = fdescp->fd_ofiles[fd];
1723 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
1724 FILEDESC_SUNLOCK(fdescp);
1725 error = EOPNOTSUPP;
1726 goto out;
1727 }
1728
1729 }
1730
1731 /*
1732 * Now replace the integer FDs with pointers to the
1733 * associated global file table entry..
1734 */
1735 newlen = oldfds * sizeof(struct file *);
1736 *controlp = sbcreatecontrol(NULL, newlen,
1737 SCM_RIGHTS, SOL_SOCKET);
1738 if (*controlp == NULL) {
1739 FILEDESC_SUNLOCK(fdescp);
1740 error = E2BIG;
1741 goto out;
1742 }
1743 fdp = data;
1744 rp = (struct file **)
1745 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1746 for (i = 0; i < oldfds; i++) {
1747 fp = fdescp->fd_ofiles[*fdp++];
1748 *rp++ = fp;
1749 FILE_LOCK(fp);
1750 fp->f_count++;
1751 fp->f_msgcount++;
1752 FILE_UNLOCK(fp);
1753 UNP_GLOBAL_WLOCK();
1754 unp_rights++;
1755 UNP_GLOBAL_WUNLOCK();
1756 }
1757 FILEDESC_SUNLOCK(fdescp);
1758 break;
1759
1760 case SCM_TIMESTAMP:
1761 *controlp = sbcreatecontrol(NULL, sizeof(*tv),
1762 SCM_TIMESTAMP, SOL_SOCKET);
1763 if (*controlp == NULL) {
1764 error = ENOBUFS;
1765 goto out;
1766 }
1767 tv = (struct timeval *)
1768 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1769 microtime(tv);
1770 break;
1771
1772 default:
1773 error = EINVAL;
1774 goto out;
1775 }
1776
1777 controlp = &(*controlp)->m_next;
1778 if (CMSG_SPACE(datalen) < clen) {
1779 clen -= CMSG_SPACE(datalen);
1780 cm = (struct cmsghdr *)
1781 ((caddr_t)cm + CMSG_SPACE(datalen));
1782 } else {
1783 clen = 0;
1784 cm = NULL;
1785 }
1786 }
1787
1788 out:
1789 m_freem(control);
1790 return (error);
1791 }
1792
1793 static struct mbuf *
1794 unp_addsockcred(struct thread *td, struct mbuf *control)
1795 {
1796 struct mbuf *m, *n, *n_prev;
1797 struct sockcred *sc;
1798 const struct cmsghdr *cm;
1799 int ngroups;
1800 int i;
1801
1802 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
1803 m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
1804 if (m == NULL)
1805 return (control);
1806
1807 sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
1808 sc->sc_uid = td->td_ucred->cr_ruid;
1809 sc->sc_euid = td->td_ucred->cr_uid;
1810 sc->sc_gid = td->td_ucred->cr_rgid;
1811 sc->sc_egid = td->td_ucred->cr_gid;
1812 sc->sc_ngroups = ngroups;
1813 for (i = 0; i < sc->sc_ngroups; i++)
1814 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
1815
1816 /*
1817 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
1818 * created SCM_CREDS control message (struct sockcred) has another
1819 * format.
1820 */
1821 if (control != NULL)
1822 for (n = control, n_prev = NULL; n != NULL;) {
1823 cm = mtod(n, struct cmsghdr *);
1824 if (cm->cmsg_level == SOL_SOCKET &&
1825 cm->cmsg_type == SCM_CREDS) {
1826 if (n_prev == NULL)
1827 control = n->m_next;
1828 else
1829 n_prev->m_next = n->m_next;
1830 n = m_free(n);
1831 } else {
1832 n_prev = n;
1833 n = n->m_next;
1834 }
1835 }
1836
1837 /* Prepend it to the head. */
1838 m->m_next = control;
1839 return (m);
1840 }
1841
1842 /*
1843 * unp_defer indicates whether additional work has been defered for a future
1844 * pass through unp_gc(). It is thread local and does not require explicit
1845 * synchronization.
1846 */
1847 static int unp_defer;
1848
1849 static int unp_taskcount;
1850 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0, "");
1851
1852 static int unp_recycled;
1853 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0, "");
1854
1855 static void
1856 unp_gc(__unused void *arg, int pending)
1857 {
1858 struct file *fp, *nextfp;
1859 struct socket *so;
1860 struct file **extra_ref, **fpp;
1861 int nunref, i;
1862 int nfiles_snap;
1863 int nfiles_slack = 20;
1864
1865 unp_taskcount++;
1866 unp_defer = 0;
1867
1868 /*
1869 * Before going through all this, set all FDs to be NOT deferred and
1870 * NOT externally accessible.
1871 */
1872 sx_slock(&filelist_lock);
1873 LIST_FOREACH(fp, &filehead, f_list)
1874 fp->f_gcflag &= ~(FMARK|FDEFER);
1875 do {
1876 KASSERT(unp_defer >= 0, ("unp_gc: unp_defer %d", unp_defer));
1877 LIST_FOREACH(fp, &filehead, f_list) {
1878 FILE_LOCK(fp);
1879 /*
1880 * If the file is not open, skip it -- could be a
1881 * file in the process of being opened, or in the
1882 * process of being closed. If the file is
1883 * "closing", it may have been marked for deferred
1884 * consideration. Clear the flag now if so.
1885 */
1886 if (fp->f_count == 0) {
1887 if (fp->f_gcflag & FDEFER)
1888 unp_defer--;
1889 fp->f_gcflag &= ~(FMARK|FDEFER);
1890 FILE_UNLOCK(fp);
1891 continue;
1892 }
1893
1894 /*
1895 * If we already marked it as 'defer' in a
1896 * previous pass, then try to process it this
1897 * time and un-mark it.
1898 */
1899 if (fp->f_gcflag & FDEFER) {
1900 fp->f_gcflag &= ~FDEFER;
1901 unp_defer--;
1902 } else {
1903 /*
1904 * If it's not deferred, then check if it's
1905 * already marked.. if so skip it
1906 */
1907 if (fp->f_gcflag & FMARK) {
1908 FILE_UNLOCK(fp);
1909 continue;
1910 }
1911
1912 /*
1913 * If all references are from messages in
1914 * transit, then skip it. it's not externally
1915 * accessible.
1916 */
1917 if (fp->f_count == fp->f_msgcount) {
1918 FILE_UNLOCK(fp);
1919 continue;
1920 }
1921
1922 /*
1923 * If it got this far then it must be
1924 * externally accessible.
1925 */
1926 fp->f_gcflag |= FMARK;
1927 }
1928
1929 /*
1930 * Either it was deferred, or it is externally
1931 * accessible and not already marked so. Now check
1932 * if it is possibly one of OUR sockets.
1933 */
1934 if (fp->f_type != DTYPE_SOCKET ||
1935 (so = fp->f_data) == NULL) {
1936 FILE_UNLOCK(fp);
1937 continue;
1938 }
1939
1940 if (so->so_proto->pr_domain != &localdomain ||
1941 (so->so_proto->pr_flags & PR_RIGHTS) == 0) {
1942 FILE_UNLOCK(fp);
1943 continue;
1944 }
1945
1946 /*
1947 * Tell any other threads that do a subsequent
1948 * fdrop() that we are scanning the message
1949 * buffers.
1950 */
1951 fp->f_gcflag |= FWAIT;
1952 FILE_UNLOCK(fp);
1953
1954 /*
1955 * So, Ok, it's one of our sockets and it IS
1956 * externally accessible (or was deferred). Now we
1957 * look to see if we hold any file descriptors in its
1958 * message buffers. Follow those links and mark them
1959 * as accessible too.
1960 */
1961 SOCKBUF_LOCK(&so->so_rcv);
1962 unp_scan(so->so_rcv.sb_mb, unp_mark);
1963 SOCKBUF_UNLOCK(&so->so_rcv);
1964
1965 /*
1966 * Wake up any threads waiting in fdrop().
1967 */
1968 FILE_LOCK(fp);
1969 fp->f_gcflag &= ~FWAIT;
1970 wakeup(&fp->f_gcflag);
1971 FILE_UNLOCK(fp);
1972 }
1973 } while (unp_defer);
1974 sx_sunlock(&filelist_lock);
1975
1976 /*
1977 * XXXRW: The following comments need updating for a post-SMPng and
1978 * deferred unp_gc() world, but are still generally accurate.
1979 *
1980 * We grab an extra reference to each of the file table entries that
1981 * are not otherwise accessible and then free the rights that are
1982 * stored in messages on them.
1983 *
1984 * The bug in the orginal code is a little tricky, so I'll describe
1985 * what's wrong with it here.
1986 *
1987 * It is incorrect to simply unp_discard each entry for f_msgcount
1988 * times -- consider the case of sockets A and B that contain
1989 * references to each other. On a last close of some other socket,
1990 * we trigger a gc since the number of outstanding rights (unp_rights)
1991 * is non-zero. If during the sweep phase the gc code unp_discards,
1992 * we end up doing a (full) closef on the descriptor. A closef on A
1993 * results in the following chain. Closef calls soo_close, which
1994 * calls soclose. Soclose calls first (through the switch
1995 * uipc_usrreq) unp_detach, which re-invokes unp_gc. Unp_gc simply
1996 * returns because the previous instance had set unp_gcing, and we
1997 * return all the way back to soclose, which marks the socket with
1998 * SS_NOFDREF, and then calls sofree. Sofree calls sorflush to free
1999 * up the rights that are queued in messages on the socket A, i.e.,
2000 * the reference on B. The sorflush calls via the dom_dispose switch
2001 * unp_dispose, which unp_scans with unp_discard. This second
2002 * instance of unp_discard just calls closef on B.
2003 *
2004 * Well, a similar chain occurs on B, resulting in a sorflush on B,
2005 * which results in another closef on A. Unfortunately, A is already
2006 * being closed, and the descriptor has already been marked with
2007 * SS_NOFDREF, and soclose panics at this point.
2008 *
2009 * Here, we first take an extra reference to each inaccessible
2010 * descriptor. Then, we call sorflush ourself, since we know it is a
2011 * Unix domain socket anyhow. After we destroy all the rights
2012 * carried in messages, we do a last closef to get rid of our extra
2013 * reference. This is the last close, and the unp_detach etc will
2014 * shut down the socket.
2015 *
2016 * 91/09/19, bsy@cs.cmu.edu
2017 */
2018 again:
2019 nfiles_snap = openfiles + nfiles_slack; /* some slack */
2020 extra_ref = malloc(nfiles_snap * sizeof(struct file *), M_TEMP,
2021 M_WAITOK);
2022 sx_slock(&filelist_lock);
2023 if (nfiles_snap < openfiles) {
2024 sx_sunlock(&filelist_lock);
2025 free(extra_ref, M_TEMP);
2026 nfiles_slack += 20;
2027 goto again;
2028 }
2029 for (nunref = 0, fp = LIST_FIRST(&filehead), fpp = extra_ref;
2030 fp != NULL; fp = nextfp) {
2031 nextfp = LIST_NEXT(fp, f_list);
2032 FILE_LOCK(fp);
2033
2034 /*
2035 * If it's not open, skip it
2036 */
2037 if (fp->f_count == 0) {
2038 FILE_UNLOCK(fp);
2039 continue;
2040 }
2041
2042 /*
2043 * If all refs are from msgs, and it's not marked accessible
2044 * then it must be referenced from some unreachable cycle of
2045 * (shut-down) FDs, so include it in our list of FDs to
2046 * remove.
2047 */
2048 if (fp->f_count == fp->f_msgcount && !(fp->f_gcflag & FMARK)) {
2049 *fpp++ = fp;
2050 nunref++;
2051 fp->f_count++;
2052 }
2053 FILE_UNLOCK(fp);
2054 }
2055 sx_sunlock(&filelist_lock);
2056
2057 /*
2058 * For each FD on our hit list, do the following two things:
2059 */
2060 for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
2061 struct file *tfp = *fpp;
2062 FILE_LOCK(tfp);
2063 if (tfp->f_type == DTYPE_SOCKET &&
2064 tfp->f_data != NULL) {
2065 FILE_UNLOCK(tfp);
2066 sorflush(tfp->f_data);
2067 } else {
2068 FILE_UNLOCK(tfp);
2069 }
2070 }
2071 for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
2072 closef(*fpp, (struct thread *) NULL);
2073 unp_recycled++;
2074 }
2075 free(extra_ref, M_TEMP);
2076 }
2077
2078 static void
2079 unp_dispose(struct mbuf *m)
2080 {
2081
2082 if (m)
2083 unp_scan(m, unp_discard);
2084 }
2085
2086 static void
2087 unp_scan(struct mbuf *m0, void (*op)(struct file *))
2088 {
2089 struct mbuf *m;
2090 struct file **rp;
2091 struct cmsghdr *cm;
2092 void *data;
2093 int i;
2094 socklen_t clen, datalen;
2095 int qfds;
2096
2097 while (m0 != NULL) {
2098 for (m = m0; m; m = m->m_next) {
2099 if (m->m_type != MT_CONTROL)
2100 continue;
2101
2102 cm = mtod(m, struct cmsghdr *);
2103 clen = m->m_len;
2104
2105 while (cm != NULL) {
2106 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2107 break;
2108
2109 data = CMSG_DATA(cm);
2110 datalen = (caddr_t)cm + cm->cmsg_len
2111 - (caddr_t)data;
2112
2113 if (cm->cmsg_level == SOL_SOCKET &&
2114 cm->cmsg_type == SCM_RIGHTS) {
2115 qfds = datalen / sizeof (struct file *);
2116 rp = data;
2117 for (i = 0; i < qfds; i++)
2118 (*op)(*rp++);
2119 }
2120
2121 if (CMSG_SPACE(datalen) < clen) {
2122 clen -= CMSG_SPACE(datalen);
2123 cm = (struct cmsghdr *)
2124 ((caddr_t)cm + CMSG_SPACE(datalen));
2125 } else {
2126 clen = 0;
2127 cm = NULL;
2128 }
2129 }
2130 }
2131 m0 = m0->m_act;
2132 }
2133 }
2134
2135 static void
2136 unp_mark(struct file *fp)
2137 {
2138
2139 /* XXXRW: Should probably assert file list lock here. */
2140
2141 if (fp->f_gcflag & FMARK)
2142 return;
2143 unp_defer++;
2144 fp->f_gcflag |= (FMARK|FDEFER);
2145 }
2146
2147 static void
2148 unp_discard(struct file *fp)
2149 {
2150
2151 UNP_GLOBAL_WLOCK();
2152 FILE_LOCK(fp);
2153 fp->f_msgcount--;
2154 unp_rights--;
2155 FILE_UNLOCK(fp);
2156 UNP_GLOBAL_WUNLOCK();
2157 (void) closef(fp, (struct thread *)NULL);
2158 }
2159
2160 #ifdef DDB
2161 static void
2162 db_print_indent(int indent)
2163 {
2164 int i;
2165
2166 for (i = 0; i < indent; i++)
2167 db_printf(" ");
2168 }
2169
2170 static void
2171 db_print_unpflags(int unp_flags)
2172 {
2173 int comma;
2174
2175 comma = 0;
2176 if (unp_flags & UNP_HAVEPC) {
2177 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
2178 comma = 1;
2179 }
2180 if (unp_flags & UNP_HAVEPCCACHED) {
2181 db_printf("%sUNP_HAVEPCCACHED", comma ? ", " : "");
2182 comma = 1;
2183 }
2184 if (unp_flags & UNP_WANTCRED) {
2185 db_printf("%sUNP_WANTCRED", comma ? ", " : "");
2186 comma = 1;
2187 }
2188 if (unp_flags & UNP_CONNWAIT) {
2189 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
2190 comma = 1;
2191 }
2192 if (unp_flags & UNP_CONNECTING) {
2193 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
2194 comma = 1;
2195 }
2196 if (unp_flags & UNP_BINDING) {
2197 db_printf("%sUNP_BINDING", comma ? ", " : "");
2198 comma = 1;
2199 }
2200 }
2201
2202 static void
2203 db_print_xucred(int indent, struct xucred *xu)
2204 {
2205 int comma, i;
2206
2207 db_print_indent(indent);
2208 db_printf("cr_version: %u cr_uid: %u cr_ngroups: %d\n",
2209 xu->cr_version, xu->cr_uid, xu->cr_ngroups);
2210 db_print_indent(indent);
2211 db_printf("cr_groups: ");
2212 comma = 0;
2213 for (i = 0; i < xu->cr_ngroups; i++) {
2214 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
2215 comma = 1;
2216 }
2217 db_printf("\n");
2218 }
2219
2220 static void
2221 db_print_unprefs(int indent, struct unp_head *uh)
2222 {
2223 struct unpcb *unp;
2224 int counter;
2225
2226 counter = 0;
2227 LIST_FOREACH(unp, uh, unp_reflink) {
2228 if (counter % 4 == 0)
2229 db_print_indent(indent);
2230 db_printf("%p ", unp);
2231 if (counter % 4 == 3)
2232 db_printf("\n");
2233 counter++;
2234 }
2235 if (counter != 0 && counter % 4 != 0)
2236 db_printf("\n");
2237 }
2238
2239 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
2240 {
2241 struct unpcb *unp;
2242
2243 if (!have_addr) {
2244 db_printf("usage: show unpcb <addr>\n");
2245 return;
2246 }
2247 unp = (struct unpcb *)addr;
2248
2249 db_printf("unp_socket: %p unp_vnode: %p\n", unp->unp_socket,
2250 unp->unp_vnode);
2251
2252 db_printf("unp_ino: %d unp_conn: %p\n", unp->unp_ino,
2253 unp->unp_conn);
2254
2255 db_printf("unp_refs:\n");
2256 db_print_unprefs(2, &unp->unp_refs);
2257
2258 /* XXXRW: Would be nice to print the full address, if any. */
2259 db_printf("unp_addr: %p\n", unp->unp_addr);
2260
2261 db_printf("unp_cc: %d unp_mbcnt: %d unp_gencnt: %llu\n",
2262 unp->unp_cc, unp->unp_mbcnt,
2263 (unsigned long long)unp->unp_gencnt);
2264
2265 db_printf("unp_flags: %x (", unp->unp_flags);
2266 db_print_unpflags(unp->unp_flags);
2267 db_printf(")\n");
2268
2269 db_printf("unp_peercred:\n");
2270 db_print_xucred(2, &unp->unp_peercred);
2271
2272 db_printf("unp_refcount: %u\n", unp->unp_refcount);
2273 }
2274 #endif
Cache object: 2f039cec81e1bf0c3389321eefd950f6
|