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_dgram, uipc_usrreqs_stream;
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_stream
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_dgram
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 if (soun->sun_len > sizeof(struct sockaddr_un))
399 return (EINVAL);
400 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
401 if (namelen <= 0)
402 return (EINVAL);
403
404 /*
405 * We don't allow simultaneous bind() calls on a single UNIX domain
406 * socket, so flag in-progress operations, and return an error if an
407 * operation is already in progress.
408 *
409 * Historically, we have not allowed a socket to be rebound, so this
410 * also returns an error. Not allowing re-binding simplifies the
411 * implementation and avoids a great many possible failure modes.
412 */
413 UNP_PCB_LOCK(unp);
414 if (unp->unp_vnode != NULL) {
415 UNP_PCB_UNLOCK(unp);
416 return (EINVAL);
417 }
418 if (unp->unp_flags & UNP_BINDING) {
419 UNP_PCB_UNLOCK(unp);
420 return (EALREADY);
421 }
422 unp->unp_flags |= UNP_BINDING;
423 UNP_PCB_UNLOCK(unp);
424
425 buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
426 bcopy(soun->sun_path, buf, namelen);
427 buf[namelen] = 0;
428
429 restart:
430 vfslocked = 0;
431 NDINIT(&nd, CREATE, MPSAFE | NOFOLLOW | LOCKPARENT | SAVENAME,
432 UIO_SYSSPACE, buf, td);
433 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
434 error = namei(&nd);
435 if (error)
436 goto error;
437 vp = nd.ni_vp;
438 vfslocked = NDHASGIANT(&nd);
439 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
440 NDFREE(&nd, NDF_ONLY_PNBUF);
441 if (nd.ni_dvp == vp)
442 vrele(nd.ni_dvp);
443 else
444 vput(nd.ni_dvp);
445 if (vp != NULL) {
446 vrele(vp);
447 error = EADDRINUSE;
448 goto error;
449 }
450 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
451 if (error)
452 goto error;
453 VFS_UNLOCK_GIANT(vfslocked);
454 goto restart;
455 }
456 VATTR_NULL(&vattr);
457 vattr.va_type = VSOCK;
458 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
459 #ifdef MAC
460 error = mac_check_vnode_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
461 &vattr);
462 #endif
463 if (error == 0) {
464 VOP_LEASE(nd.ni_dvp, td, td->td_ucred, LEASE_WRITE);
465 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
466 }
467 NDFREE(&nd, NDF_ONLY_PNBUF);
468 vput(nd.ni_dvp);
469 if (error) {
470 vn_finished_write(mp);
471 goto error;
472 }
473 vp = nd.ni_vp;
474 ASSERT_VOP_ELOCKED(vp, "uipc_bind");
475 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
476
477 UNP_GLOBAL_WLOCK();
478 UNP_PCB_LOCK(unp);
479 vp->v_socket = unp->unp_socket;
480 unp->unp_vnode = vp;
481 unp->unp_addr = soun;
482 unp->unp_flags &= ~UNP_BINDING;
483 UNP_PCB_UNLOCK(unp);
484 UNP_GLOBAL_WUNLOCK();
485 VOP_UNLOCK(vp, 0, td);
486 vn_finished_write(mp);
487 VFS_UNLOCK_GIANT(vfslocked);
488 free(buf, M_TEMP);
489 return (0);
490
491 error:
492 VFS_UNLOCK_GIANT(vfslocked);
493 UNP_PCB_LOCK(unp);
494 unp->unp_flags &= ~UNP_BINDING;
495 UNP_PCB_UNLOCK(unp);
496 free(buf, M_TEMP);
497 return (error);
498 }
499
500 static int
501 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
502 {
503 int error;
504
505 KASSERT(td == curthread, ("uipc_connect: td != curthread"));
506 UNP_GLOBAL_WLOCK();
507 error = unp_connect(so, nam, td);
508 UNP_GLOBAL_WUNLOCK();
509 return (error);
510 }
511
512 static void
513 uipc_close(struct socket *so)
514 {
515 struct unpcb *unp, *unp2;
516
517 unp = sotounpcb(so);
518 KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
519
520 UNP_GLOBAL_WLOCK();
521 UNP_PCB_LOCK(unp);
522 unp2 = unp->unp_conn;
523 if (unp2 != NULL) {
524 UNP_PCB_LOCK(unp2);
525 unp_disconnect(unp, unp2);
526 UNP_PCB_UNLOCK(unp2);
527 }
528 UNP_PCB_UNLOCK(unp);
529 UNP_GLOBAL_WUNLOCK();
530 }
531
532 static int
533 uipc_connect2(struct socket *so1, struct socket *so2)
534 {
535 struct unpcb *unp, *unp2;
536 int error;
537
538 UNP_GLOBAL_WLOCK();
539 unp = so1->so_pcb;
540 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
541 UNP_PCB_LOCK(unp);
542 unp2 = so2->so_pcb;
543 KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
544 UNP_PCB_LOCK(unp2);
545 error = unp_connect2(so1, so2, PRU_CONNECT2);
546 UNP_PCB_UNLOCK(unp2);
547 UNP_PCB_UNLOCK(unp);
548 UNP_GLOBAL_WUNLOCK();
549 return (error);
550 }
551
552 static void
553 uipc_detach(struct socket *so)
554 {
555 struct unpcb *unp, *unp2;
556 struct sockaddr_un *saved_unp_addr;
557 struct vnode *vp;
558 int freeunp, local_unp_rights;
559
560 unp = sotounpcb(so);
561 KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
562
563 UNP_GLOBAL_WLOCK();
564 UNP_PCB_LOCK(unp);
565
566 LIST_REMOVE(unp, unp_link);
567 unp->unp_gencnt = ++unp_gencnt;
568 --unp_count;
569
570 /*
571 * XXXRW: Should assert vp->v_socket == so.
572 */
573 if ((vp = unp->unp_vnode) != NULL) {
574 unp->unp_vnode->v_socket = NULL;
575 unp->unp_vnode = NULL;
576 }
577 unp2 = unp->unp_conn;
578 if (unp2 != NULL) {
579 UNP_PCB_LOCK(unp2);
580 unp_disconnect(unp, unp2);
581 UNP_PCB_UNLOCK(unp2);
582 }
583
584 /*
585 * We hold the global lock exclusively, so it's OK to acquire
586 * multiple pcb locks at a time.
587 */
588 while (!LIST_EMPTY(&unp->unp_refs)) {
589 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
590
591 UNP_PCB_LOCK(ref);
592 unp_drop(ref, ECONNRESET);
593 UNP_PCB_UNLOCK(ref);
594 }
595 local_unp_rights = unp_rights;
596 UNP_GLOBAL_WUNLOCK();
597 unp->unp_socket->so_pcb = NULL;
598 saved_unp_addr = unp->unp_addr;
599 unp->unp_addr = NULL;
600 unp->unp_refcount--;
601 freeunp = (unp->unp_refcount == 0);
602 if (saved_unp_addr != NULL)
603 FREE(saved_unp_addr, M_SONAME);
604 if (freeunp) {
605 UNP_PCB_LOCK_DESTROY(unp);
606 uma_zfree(unp_zone, unp);
607 } else
608 UNP_PCB_UNLOCK(unp);
609 if (vp) {
610 int vfslocked;
611
612 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
613 vrele(vp);
614 VFS_UNLOCK_GIANT(vfslocked);
615 }
616 if (local_unp_rights)
617 taskqueue_enqueue(taskqueue_thread, &unp_gc_task);
618 }
619
620 static int
621 uipc_disconnect(struct socket *so)
622 {
623 struct unpcb *unp, *unp2;
624
625 unp = sotounpcb(so);
626 KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
627
628 UNP_GLOBAL_WLOCK();
629 UNP_PCB_LOCK(unp);
630 unp2 = unp->unp_conn;
631 if (unp2 != NULL) {
632 UNP_PCB_LOCK(unp2);
633 unp_disconnect(unp, unp2);
634 UNP_PCB_UNLOCK(unp2);
635 }
636 UNP_PCB_UNLOCK(unp);
637 UNP_GLOBAL_WUNLOCK();
638 return (0);
639 }
640
641 static int
642 uipc_listen(struct socket *so, int backlog, struct thread *td)
643 {
644 struct unpcb *unp;
645 int error;
646
647 unp = sotounpcb(so);
648 KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
649
650 UNP_PCB_LOCK(unp);
651 if (unp->unp_vnode == NULL) {
652 UNP_PCB_UNLOCK(unp);
653 return (EINVAL);
654 }
655
656 SOCK_LOCK(so);
657 error = solisten_proto_check(so);
658 if (error == 0) {
659 cru2x(td->td_ucred, &unp->unp_peercred);
660 unp->unp_flags |= UNP_HAVEPCCACHED;
661 solisten_proto(so, backlog);
662 }
663 SOCK_UNLOCK(so);
664 UNP_PCB_UNLOCK(unp);
665 return (error);
666 }
667
668 static int
669 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
670 {
671 struct unpcb *unp, *unp2;
672 const struct sockaddr *sa;
673
674 unp = sotounpcb(so);
675 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
676
677 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
678 UNP_GLOBAL_RLOCK();
679 /*
680 * XXX: It seems that this test always fails even when connection is
681 * established. So, this else clause is added as workaround to
682 * return PF_LOCAL sockaddr.
683 */
684 unp2 = unp->unp_conn;
685 if (unp2 != NULL) {
686 UNP_PCB_LOCK(unp2);
687 if (unp2->unp_addr != NULL)
688 sa = (struct sockaddr *) unp2->unp_addr;
689 else
690 sa = &sun_noname;
691 bcopy(sa, *nam, sa->sa_len);
692 UNP_PCB_UNLOCK(unp2);
693 } else {
694 sa = &sun_noname;
695 bcopy(sa, *nam, sa->sa_len);
696 }
697 UNP_GLOBAL_RUNLOCK();
698 return (0);
699 }
700
701 static int
702 uipc_rcvd(struct socket *so, int flags)
703 {
704 struct unpcb *unp, *unp2;
705 struct socket *so2;
706 u_int mbcnt, sbcc;
707 u_long newhiwat;
708
709 unp = sotounpcb(so);
710 KASSERT(unp != NULL, ("uipc_rcvd: unp == NULL"));
711
712 if (so->so_type == SOCK_DGRAM)
713 panic("uipc_rcvd DGRAM?");
714
715 if (so->so_type != SOCK_STREAM)
716 panic("uipc_rcvd unknown socktype");
717
718 /*
719 * Adjust backpressure on sender and wakeup any waiting to write.
720 *
721 * The unp lock is acquired to maintain the validity of the unp_conn
722 * pointer; no lock on unp2 is required as unp2->unp_socket will be
723 * static as long as we don't permit unp2 to disconnect from unp,
724 * which is prevented by the lock on unp. We cache values from
725 * so_rcv to avoid holding the so_rcv lock over the entire
726 * transaction on the remote so_snd.
727 */
728 SOCKBUF_LOCK(&so->so_rcv);
729 mbcnt = so->so_rcv.sb_mbcnt;
730 sbcc = so->so_rcv.sb_cc;
731 SOCKBUF_UNLOCK(&so->so_rcv);
732 UNP_PCB_LOCK(unp);
733 unp2 = unp->unp_conn;
734 if (unp2 == NULL) {
735 UNP_PCB_UNLOCK(unp);
736 return (0);
737 }
738 so2 = unp2->unp_socket;
739 SOCKBUF_LOCK(&so2->so_snd);
740 so2->so_snd.sb_mbmax += unp->unp_mbcnt - mbcnt;
741 newhiwat = so2->so_snd.sb_hiwat + unp->unp_cc - sbcc;
742 (void)chgsbsize(so2->so_cred->cr_uidinfo, &so2->so_snd.sb_hiwat,
743 newhiwat, RLIM_INFINITY);
744 sowwakeup_locked(so2);
745 unp->unp_mbcnt = mbcnt;
746 unp->unp_cc = sbcc;
747 UNP_PCB_UNLOCK(unp);
748 return (0);
749 }
750
751 static int
752 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
753 struct mbuf *control, struct thread *td)
754 {
755 struct unpcb *unp, *unp2;
756 struct socket *so2;
757 u_int mbcnt_delta, sbcc;
758 u_long newhiwat;
759 int error = 0;
760
761 unp = sotounpcb(so);
762 KASSERT(unp != NULL, ("uipc_send: unp == NULL"));
763
764 if (flags & PRUS_OOB) {
765 error = EOPNOTSUPP;
766 goto release;
767 }
768 if (control != NULL && (error = unp_internalize(&control, td)))
769 goto release;
770 if ((nam != NULL) || (flags & PRUS_EOF))
771 UNP_GLOBAL_WLOCK();
772 else
773 UNP_GLOBAL_RLOCK();
774 switch (so->so_type) {
775 case SOCK_DGRAM:
776 {
777 const struct sockaddr *from;
778
779 unp2 = unp->unp_conn;
780 if (nam != NULL) {
781 UNP_GLOBAL_WLOCK_ASSERT();
782 if (unp2 != NULL) {
783 error = EISCONN;
784 break;
785 }
786 error = unp_connect(so, nam, td);
787 if (error)
788 break;
789 unp2 = unp->unp_conn;
790 }
791
792 /*
793 * Because connect() and send() are non-atomic in a sendto()
794 * with a target address, it's possible that the socket will
795 * have disconnected before the send() can run. In that case
796 * return the slightly counter-intuitive but otherwise
797 * correct error that the socket is not connected.
798 */
799 if (unp2 == NULL) {
800 error = ENOTCONN;
801 break;
802 }
803 /* Lockless read. */
804 if (unp2->unp_flags & UNP_WANTCRED)
805 control = unp_addsockcred(td, control);
806 UNP_PCB_LOCK(unp);
807 if (unp->unp_addr != NULL)
808 from = (struct sockaddr *)unp->unp_addr;
809 else
810 from = &sun_noname;
811 so2 = unp2->unp_socket;
812 SOCKBUF_LOCK(&so2->so_rcv);
813 if (sbappendaddr_locked(&so2->so_rcv, from, m, control)) {
814 sorwakeup_locked(so2);
815 m = NULL;
816 control = NULL;
817 } else {
818 SOCKBUF_UNLOCK(&so2->so_rcv);
819 error = ENOBUFS;
820 }
821 if (nam != NULL) {
822 UNP_GLOBAL_WLOCK_ASSERT();
823 UNP_PCB_LOCK(unp2);
824 unp_disconnect(unp, unp2);
825 UNP_PCB_UNLOCK(unp2);
826 }
827 UNP_PCB_UNLOCK(unp);
828 break;
829 }
830
831 case SOCK_STREAM:
832 if ((so->so_state & SS_ISCONNECTED) == 0) {
833 if (nam != NULL) {
834 UNP_GLOBAL_WLOCK_ASSERT();
835 error = unp_connect(so, nam, td);
836 if (error)
837 break; /* XXX */
838 } else {
839 error = ENOTCONN;
840 break;
841 }
842 }
843
844 /* Lockless read. */
845 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
846 error = EPIPE;
847 break;
848 }
849
850 /*
851 * Because connect() and send() are non-atomic in a sendto()
852 * with a target address, it's possible that the socket will
853 * have disconnected before the send() can run. In that case
854 * return the slightly counter-intuitive but otherwise
855 * correct error that the socket is not connected.
856 *
857 * Locking here must be done carefully: the global lock
858 * prevents interconnections between unpcbs from changing, so
859 * we can traverse from unp to unp2 without acquiring unp's
860 * lock. Socket buffer locks follow unpcb locks, so we can
861 * acquire both remote and lock socket buffer locks.
862 */
863 unp2 = unp->unp_conn;
864 if (unp2 == NULL) {
865 error = ENOTCONN;
866 break;
867 }
868 so2 = unp2->unp_socket;
869 UNP_PCB_LOCK(unp2);
870 SOCKBUF_LOCK(&so2->so_rcv);
871 if (unp2->unp_flags & UNP_WANTCRED) {
872 /*
873 * Credentials are passed only once on SOCK_STREAM.
874 */
875 unp2->unp_flags &= ~UNP_WANTCRED;
876 control = unp_addsockcred(td, control);
877 }
878 /*
879 * Send to paired receive port, and then reduce send buffer
880 * hiwater marks to maintain backpressure. Wake up readers.
881 */
882 if (control != NULL) {
883 if (sbappendcontrol_locked(&so2->so_rcv, m, control))
884 control = NULL;
885 } else
886 sbappend_locked(&so2->so_rcv, m);
887 mbcnt_delta = so2->so_rcv.sb_mbcnt - unp2->unp_mbcnt;
888 unp2->unp_mbcnt = so2->so_rcv.sb_mbcnt;
889 sbcc = so2->so_rcv.sb_cc;
890 sorwakeup_locked(so2);
891
892 SOCKBUF_LOCK(&so->so_snd);
893 newhiwat = so->so_snd.sb_hiwat - (sbcc - unp2->unp_cc);
894 (void)chgsbsize(so->so_cred->cr_uidinfo, &so->so_snd.sb_hiwat,
895 newhiwat, RLIM_INFINITY);
896 so->so_snd.sb_mbmax -= mbcnt_delta;
897 SOCKBUF_UNLOCK(&so->so_snd);
898 unp2->unp_cc = sbcc;
899 UNP_PCB_UNLOCK(unp2);
900 m = NULL;
901 break;
902
903 default:
904 panic("uipc_send unknown socktype");
905 }
906
907 /*
908 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
909 */
910 if (flags & PRUS_EOF) {
911 UNP_PCB_LOCK(unp);
912 socantsendmore(so);
913 unp_shutdown(unp);
914 UNP_PCB_UNLOCK(unp);
915 }
916
917 if ((nam != NULL) || (flags & PRUS_EOF))
918 UNP_GLOBAL_WUNLOCK();
919 else
920 UNP_GLOBAL_RUNLOCK();
921
922 if (control != NULL && error != 0)
923 unp_dispose(control);
924
925 release:
926 if (control != NULL)
927 m_freem(control);
928 if (m != NULL)
929 m_freem(m);
930 return (error);
931 }
932
933 static int
934 uipc_sense(struct socket *so, struct stat *sb)
935 {
936 struct unpcb *unp, *unp2;
937 struct socket *so2;
938
939 unp = sotounpcb(so);
940 KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
941
942 sb->st_blksize = so->so_snd.sb_hiwat;
943 UNP_GLOBAL_RLOCK();
944 UNP_PCB_LOCK(unp);
945 unp2 = unp->unp_conn;
946 if (so->so_type == SOCK_STREAM && unp2 != NULL) {
947 so2 = unp2->unp_socket;
948 sb->st_blksize += so2->so_rcv.sb_cc;
949 }
950 sb->st_dev = NODEV;
951 if (unp->unp_ino == 0)
952 unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
953 sb->st_ino = unp->unp_ino;
954 UNP_PCB_UNLOCK(unp);
955 UNP_GLOBAL_RUNLOCK();
956 return (0);
957 }
958
959 static int
960 uipc_shutdown(struct socket *so)
961 {
962 struct unpcb *unp;
963
964 unp = sotounpcb(so);
965 KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
966
967 UNP_GLOBAL_WLOCK();
968 UNP_PCB_LOCK(unp);
969 socantsendmore(so);
970 unp_shutdown(unp);
971 UNP_PCB_UNLOCK(unp);
972 UNP_GLOBAL_WUNLOCK();
973 return (0);
974 }
975
976 static int
977 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
978 {
979 struct unpcb *unp;
980 const struct sockaddr *sa;
981
982 unp = sotounpcb(so);
983 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
984
985 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
986 UNP_PCB_LOCK(unp);
987 if (unp->unp_addr != NULL)
988 sa = (struct sockaddr *) unp->unp_addr;
989 else
990 sa = &sun_noname;
991 bcopy(sa, *nam, sa->sa_len);
992 UNP_PCB_UNLOCK(unp);
993 return (0);
994 }
995
996 static struct pr_usrreqs uipc_usrreqs_dgram = {
997 .pru_abort = uipc_abort,
998 .pru_accept = uipc_accept,
999 .pru_attach = uipc_attach,
1000 .pru_bind = uipc_bind,
1001 .pru_connect = uipc_connect,
1002 .pru_connect2 = uipc_connect2,
1003 .pru_detach = uipc_detach,
1004 .pru_disconnect = uipc_disconnect,
1005 .pru_listen = uipc_listen,
1006 .pru_peeraddr = uipc_peeraddr,
1007 .pru_rcvd = uipc_rcvd,
1008 .pru_send = uipc_send,
1009 .pru_sense = uipc_sense,
1010 .pru_shutdown = uipc_shutdown,
1011 .pru_sockaddr = uipc_sockaddr,
1012 .pru_soreceive = soreceive_dgram,
1013 .pru_close = uipc_close,
1014 };
1015
1016 static struct pr_usrreqs uipc_usrreqs_stream = {
1017 .pru_abort = uipc_abort,
1018 .pru_accept = uipc_accept,
1019 .pru_attach = uipc_attach,
1020 .pru_bind = uipc_bind,
1021 .pru_connect = uipc_connect,
1022 .pru_connect2 = uipc_connect2,
1023 .pru_detach = uipc_detach,
1024 .pru_disconnect = uipc_disconnect,
1025 .pru_listen = uipc_listen,
1026 .pru_peeraddr = uipc_peeraddr,
1027 .pru_rcvd = uipc_rcvd,
1028 .pru_send = uipc_send,
1029 .pru_sense = uipc_sense,
1030 .pru_shutdown = uipc_shutdown,
1031 .pru_sockaddr = uipc_sockaddr,
1032 .pru_soreceive = soreceive_generic,
1033 .pru_close = uipc_close,
1034 };
1035
1036 static int
1037 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1038 {
1039 struct unpcb *unp;
1040 struct xucred xu;
1041 int error, optval;
1042
1043 if (sopt->sopt_level != 0)
1044 return (EINVAL);
1045
1046 unp = sotounpcb(so);
1047 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1048 error = 0;
1049 switch (sopt->sopt_dir) {
1050 case SOPT_GET:
1051 switch (sopt->sopt_name) {
1052 case LOCAL_PEERCRED:
1053 UNP_PCB_LOCK(unp);
1054 if (unp->unp_flags & UNP_HAVEPC)
1055 xu = unp->unp_peercred;
1056 else {
1057 if (so->so_type == SOCK_STREAM)
1058 error = ENOTCONN;
1059 else
1060 error = EINVAL;
1061 }
1062 UNP_PCB_UNLOCK(unp);
1063 if (error == 0)
1064 error = sooptcopyout(sopt, &xu, sizeof(xu));
1065 break;
1066
1067 case LOCAL_CREDS:
1068 /* Unlocked read. */
1069 optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
1070 error = sooptcopyout(sopt, &optval, sizeof(optval));
1071 break;
1072
1073 case LOCAL_CONNWAIT:
1074 /* Unlocked read. */
1075 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1076 error = sooptcopyout(sopt, &optval, sizeof(optval));
1077 break;
1078
1079 default:
1080 error = EOPNOTSUPP;
1081 break;
1082 }
1083 break;
1084
1085 case SOPT_SET:
1086 switch (sopt->sopt_name) {
1087 case LOCAL_CREDS:
1088 case LOCAL_CONNWAIT:
1089 error = sooptcopyin(sopt, &optval, sizeof(optval),
1090 sizeof(optval));
1091 if (error)
1092 break;
1093
1094 #define OPTSET(bit) do { \
1095 UNP_PCB_LOCK(unp); \
1096 if (optval) \
1097 unp->unp_flags |= bit; \
1098 else \
1099 unp->unp_flags &= ~bit; \
1100 UNP_PCB_UNLOCK(unp); \
1101 } while (0)
1102
1103 switch (sopt->sopt_name) {
1104 case LOCAL_CREDS:
1105 OPTSET(UNP_WANTCRED);
1106 break;
1107
1108 case LOCAL_CONNWAIT:
1109 OPTSET(UNP_CONNWAIT);
1110 break;
1111
1112 default:
1113 break;
1114 }
1115 break;
1116 #undef OPTSET
1117 default:
1118 error = ENOPROTOOPT;
1119 break;
1120 }
1121 break;
1122
1123 default:
1124 error = EOPNOTSUPP;
1125 break;
1126 }
1127 return (error);
1128 }
1129
1130 static int
1131 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1132 {
1133 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
1134 struct vnode *vp;
1135 struct socket *so2, *so3;
1136 struct unpcb *unp, *unp2, *unp3;
1137 int error, len, vfslocked;
1138 struct nameidata nd;
1139 char buf[SOCK_MAXADDRLEN];
1140 struct sockaddr *sa;
1141
1142 UNP_GLOBAL_WLOCK_ASSERT();
1143
1144 unp = sotounpcb(so);
1145 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1146
1147 if (nam->sa_len > sizeof(struct sockaddr_un))
1148 return (EINVAL);
1149 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1150 if (len <= 0)
1151 return (EINVAL);
1152 bcopy(soun->sun_path, buf, len);
1153 buf[len] = 0;
1154
1155 UNP_PCB_LOCK(unp);
1156 if (unp->unp_flags & UNP_CONNECTING) {
1157 UNP_PCB_UNLOCK(unp);
1158 return (EALREADY);
1159 }
1160 UNP_GLOBAL_WUNLOCK();
1161 unp->unp_flags |= UNP_CONNECTING;
1162 UNP_PCB_UNLOCK(unp);
1163
1164 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1165 NDINIT(&nd, LOOKUP, MPSAFE | FOLLOW | LOCKLEAF, UIO_SYSSPACE, buf,
1166 td);
1167 error = namei(&nd);
1168 if (error)
1169 vp = NULL;
1170 else
1171 vp = nd.ni_vp;
1172 ASSERT_VOP_LOCKED(vp, "unp_connect");
1173 vfslocked = NDHASGIANT(&nd);
1174 NDFREE(&nd, NDF_ONLY_PNBUF);
1175 if (error)
1176 goto bad;
1177
1178 if (vp->v_type != VSOCK) {
1179 error = ENOTSOCK;
1180 goto bad;
1181 }
1182 #ifdef MAC
1183 error = mac_check_vnode_open(td->td_ucred, vp, VWRITE | VREAD);
1184 if (error)
1185 goto bad;
1186 #endif
1187 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1188 if (error)
1189 goto bad;
1190 VFS_UNLOCK_GIANT(vfslocked);
1191
1192 unp = sotounpcb(so);
1193 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1194
1195 /*
1196 * Lock global lock for two reasons: make sure v_socket is stable,
1197 * and to protect simultaneous locking of multiple pcbs.
1198 */
1199 UNP_GLOBAL_WLOCK();
1200 so2 = vp->v_socket;
1201 if (so2 == NULL) {
1202 error = ECONNREFUSED;
1203 goto bad2;
1204 }
1205 if (so->so_type != so2->so_type) {
1206 error = EPROTOTYPE;
1207 goto bad2;
1208 }
1209 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
1210 if (so2->so_options & SO_ACCEPTCONN) {
1211 /*
1212 * We can't drop the global lock here or 'so2' may
1213 * become invalid. As a result, we need to handle
1214 * possibly lock recursion in uipc_attach.
1215 */
1216 so3 = sonewconn(so2, 0);
1217 } else
1218 so3 = NULL;
1219 if (so3 == NULL) {
1220 error = ECONNREFUSED;
1221 goto bad2;
1222 }
1223 unp = sotounpcb(so);
1224 unp2 = sotounpcb(so2);
1225 unp3 = sotounpcb(so3);
1226 UNP_PCB_LOCK(unp);
1227 UNP_PCB_LOCK(unp2);
1228 UNP_PCB_LOCK(unp3);
1229 if (unp2->unp_addr != NULL) {
1230 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1231 unp3->unp_addr = (struct sockaddr_un *) sa;
1232 sa = NULL;
1233 }
1234
1235 /*
1236 * The connecter's (client's) credentials are copied from its
1237 * process structure at the time of connect() (which is now).
1238 */
1239 cru2x(td->td_ucred, &unp3->unp_peercred);
1240 unp3->unp_flags |= UNP_HAVEPC;
1241
1242 /*
1243 * The receiver's (server's) credentials are copied from the
1244 * unp_peercred member of socket on which the former called
1245 * listen(); uipc_listen() cached that process's credentials
1246 * at that time so we can use them now.
1247 */
1248 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
1249 ("unp_connect: listener without cached peercred"));
1250 memcpy(&unp->unp_peercred, &unp2->unp_peercred,
1251 sizeof(unp->unp_peercred));
1252 unp->unp_flags |= UNP_HAVEPC;
1253 if (unp2->unp_flags & UNP_WANTCRED)
1254 unp3->unp_flags |= UNP_WANTCRED;
1255 UNP_PCB_UNLOCK(unp3);
1256 UNP_PCB_UNLOCK(unp2);
1257 UNP_PCB_UNLOCK(unp);
1258 #ifdef MAC
1259 SOCK_LOCK(so);
1260 mac_set_socket_peer_from_socket(so, so3);
1261 mac_set_socket_peer_from_socket(so3, so);
1262 SOCK_UNLOCK(so);
1263 #endif
1264
1265 so2 = so3;
1266 }
1267 unp = sotounpcb(so);
1268 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1269 unp2 = sotounpcb(so2);
1270 KASSERT(unp2 != NULL, ("unp_connect: unp2 == NULL"));
1271 UNP_PCB_LOCK(unp);
1272 UNP_PCB_LOCK(unp2);
1273 error = unp_connect2(so, so2, PRU_CONNECT);
1274 UNP_PCB_UNLOCK(unp2);
1275 UNP_PCB_UNLOCK(unp);
1276 bad2:
1277 UNP_GLOBAL_WUNLOCK();
1278 if (vfslocked)
1279 /*
1280 * Giant has been previously acquired. This means filesystem
1281 * isn't MPSAFE. Do it once again.
1282 */
1283 mtx_lock(&Giant);
1284 bad:
1285 if (vp != NULL)
1286 vput(vp);
1287 VFS_UNLOCK_GIANT(vfslocked);
1288 free(sa, M_SONAME);
1289 UNP_GLOBAL_WLOCK();
1290 UNP_PCB_LOCK(unp);
1291 unp->unp_flags &= ~UNP_CONNECTING;
1292 UNP_PCB_UNLOCK(unp);
1293 return (error);
1294 }
1295
1296 static int
1297 unp_connect2(struct socket *so, struct socket *so2, int req)
1298 {
1299 struct unpcb *unp;
1300 struct unpcb *unp2;
1301
1302 unp = sotounpcb(so);
1303 KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1304 unp2 = sotounpcb(so2);
1305 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1306
1307 UNP_GLOBAL_WLOCK_ASSERT();
1308 UNP_PCB_LOCK_ASSERT(unp);
1309 UNP_PCB_LOCK_ASSERT(unp2);
1310
1311 if (so2->so_type != so->so_type)
1312 return (EPROTOTYPE);
1313 unp->unp_conn = unp2;
1314
1315 switch (so->so_type) {
1316 case SOCK_DGRAM:
1317 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1318 soisconnected(so);
1319 break;
1320
1321 case SOCK_STREAM:
1322 unp2->unp_conn = unp;
1323 if (req == PRU_CONNECT &&
1324 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1325 soisconnecting(so);
1326 else
1327 soisconnected(so);
1328 soisconnected(so2);
1329 break;
1330
1331 default:
1332 panic("unp_connect2");
1333 }
1334 return (0);
1335 }
1336
1337 static void
1338 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1339 {
1340 struct socket *so;
1341
1342 KASSERT(unp2 != NULL, ("unp_disconnect: unp2 == NULL"));
1343
1344 UNP_GLOBAL_WLOCK_ASSERT();
1345 UNP_PCB_LOCK_ASSERT(unp);
1346 UNP_PCB_LOCK_ASSERT(unp2);
1347
1348 unp->unp_conn = NULL;
1349 switch (unp->unp_socket->so_type) {
1350 case SOCK_DGRAM:
1351 LIST_REMOVE(unp, unp_reflink);
1352 so = unp->unp_socket;
1353 SOCK_LOCK(so);
1354 so->so_state &= ~SS_ISCONNECTED;
1355 SOCK_UNLOCK(so);
1356 break;
1357
1358 case SOCK_STREAM:
1359 soisdisconnected(unp->unp_socket);
1360 unp2->unp_conn = NULL;
1361 soisdisconnected(unp2->unp_socket);
1362 break;
1363 }
1364 }
1365
1366 /*
1367 * unp_pcblist() walks the global list of struct unpcb's to generate a
1368 * pointer list, bumping the refcount on each unpcb. It then copies them out
1369 * sequentially, validating the generation number on each to see if it has
1370 * been detached. All of this is necessary because copyout() may sleep on
1371 * disk I/O.
1372 */
1373 static int
1374 unp_pcblist(SYSCTL_HANDLER_ARGS)
1375 {
1376 int error, i, n;
1377 int freeunp;
1378 struct unpcb *unp, **unp_list;
1379 unp_gen_t gencnt;
1380 struct xunpgen *xug;
1381 struct unp_head *head;
1382 struct xunpcb *xu;
1383
1384 head = ((intptr_t)arg1 == SOCK_DGRAM ? &unp_dhead : &unp_shead);
1385
1386 /*
1387 * The process of preparing the PCB list is too time-consuming and
1388 * resource-intensive to repeat twice on every request.
1389 */
1390 if (req->oldptr == NULL) {
1391 n = unp_count;
1392 req->oldidx = 2 * (sizeof *xug)
1393 + (n + n/8) * sizeof(struct xunpcb);
1394 return (0);
1395 }
1396
1397 if (req->newptr != NULL)
1398 return (EPERM);
1399
1400 /*
1401 * OK, now we're committed to doing something.
1402 */
1403 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
1404 UNP_GLOBAL_RLOCK();
1405 gencnt = unp_gencnt;
1406 n = unp_count;
1407 UNP_GLOBAL_RUNLOCK();
1408
1409 xug->xug_len = sizeof *xug;
1410 xug->xug_count = n;
1411 xug->xug_gen = gencnt;
1412 xug->xug_sogen = so_gencnt;
1413 error = SYSCTL_OUT(req, xug, sizeof *xug);
1414 if (error) {
1415 free(xug, M_TEMP);
1416 return (error);
1417 }
1418
1419 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1420
1421 UNP_GLOBAL_RLOCK();
1422 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1423 unp = LIST_NEXT(unp, unp_link)) {
1424 UNP_PCB_LOCK(unp);
1425 if (unp->unp_gencnt <= gencnt) {
1426 if (cr_cansee(req->td->td_ucred,
1427 unp->unp_socket->so_cred)) {
1428 UNP_PCB_UNLOCK(unp);
1429 continue;
1430 }
1431 unp_list[i++] = unp;
1432 unp->unp_refcount++;
1433 }
1434 UNP_PCB_UNLOCK(unp);
1435 }
1436 UNP_GLOBAL_RUNLOCK();
1437 n = i; /* In case we lost some during malloc. */
1438
1439 error = 0;
1440 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1441 for (i = 0; i < n; i++) {
1442 unp = unp_list[i];
1443 UNP_PCB_LOCK(unp);
1444 unp->unp_refcount--;
1445 if (unp->unp_refcount != 0 && unp->unp_gencnt <= gencnt) {
1446 xu->xu_len = sizeof *xu;
1447 xu->xu_unpp = unp;
1448 /*
1449 * XXX - need more locking here to protect against
1450 * connect/disconnect races for SMP.
1451 */
1452 if (unp->unp_addr != NULL)
1453 bcopy(unp->unp_addr, &xu->xu_addr,
1454 unp->unp_addr->sun_len);
1455 if (unp->unp_conn != NULL &&
1456 unp->unp_conn->unp_addr != NULL)
1457 bcopy(unp->unp_conn->unp_addr,
1458 &xu->xu_caddr,
1459 unp->unp_conn->unp_addr->sun_len);
1460 bcopy(unp, &xu->xu_unp, sizeof *unp);
1461 sotoxsocket(unp->unp_socket, &xu->xu_socket);
1462 UNP_PCB_UNLOCK(unp);
1463 error = SYSCTL_OUT(req, xu, sizeof *xu);
1464 } else {
1465 freeunp = (unp->unp_refcount == 0);
1466 UNP_PCB_UNLOCK(unp);
1467 if (freeunp) {
1468 UNP_PCB_LOCK_DESTROY(unp);
1469 uma_zfree(unp_zone, unp);
1470 }
1471 }
1472 }
1473 free(xu, M_TEMP);
1474 if (!error) {
1475 /*
1476 * Give the user an updated idea of our state. If the
1477 * generation differs from what we told her before, she knows
1478 * that something happened while we were processing this
1479 * request, and it might be necessary to retry.
1480 */
1481 xug->xug_gen = unp_gencnt;
1482 xug->xug_sogen = so_gencnt;
1483 xug->xug_count = unp_count;
1484 error = SYSCTL_OUT(req, xug, sizeof *xug);
1485 }
1486 free(unp_list, M_TEMP);
1487 free(xug, M_TEMP);
1488 return (error);
1489 }
1490
1491 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD,
1492 (caddr_t)(long)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1493 "List of active local datagram sockets");
1494 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD,
1495 (caddr_t)(long)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1496 "List of active local stream sockets");
1497
1498 static void
1499 unp_shutdown(struct unpcb *unp)
1500 {
1501 struct unpcb *unp2;
1502 struct socket *so;
1503
1504 UNP_GLOBAL_WLOCK_ASSERT();
1505 UNP_PCB_LOCK_ASSERT(unp);
1506
1507 unp2 = unp->unp_conn;
1508 if (unp->unp_socket->so_type == SOCK_STREAM && unp2 != NULL) {
1509 so = unp2->unp_socket;
1510 if (so != NULL)
1511 socantrcvmore(so);
1512 }
1513 }
1514
1515 static void
1516 unp_drop(struct unpcb *unp, int errno)
1517 {
1518 struct socket *so = unp->unp_socket;
1519 struct unpcb *unp2;
1520
1521 UNP_GLOBAL_WLOCK_ASSERT();
1522 UNP_PCB_LOCK_ASSERT(unp);
1523
1524 so->so_error = errno;
1525 unp2 = unp->unp_conn;
1526 if (unp2 == NULL)
1527 return;
1528 UNP_PCB_LOCK(unp2);
1529 unp_disconnect(unp, unp2);
1530 UNP_PCB_UNLOCK(unp2);
1531 }
1532
1533 static void
1534 unp_freerights(struct file **rp, int fdcount)
1535 {
1536 int i;
1537 struct file *fp;
1538
1539 for (i = 0; i < fdcount; i++) {
1540 fp = *rp;
1541 *rp++ = NULL;
1542 unp_discard(fp);
1543 }
1544 }
1545
1546 static int
1547 unp_externalize(struct mbuf *control, struct mbuf **controlp)
1548 {
1549 struct thread *td = curthread; /* XXX */
1550 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1551 int i;
1552 int *fdp;
1553 struct file **rp;
1554 struct file *fp;
1555 void *data;
1556 socklen_t clen = control->m_len, datalen;
1557 int error, newfds;
1558 int f;
1559 u_int newlen;
1560
1561 UNP_GLOBAL_UNLOCK_ASSERT();
1562
1563 error = 0;
1564 if (controlp != NULL) /* controlp == NULL => free control messages */
1565 *controlp = NULL;
1566 while (cm != NULL) {
1567 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1568 error = EINVAL;
1569 break;
1570 }
1571 data = CMSG_DATA(cm);
1572 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1573 if (cm->cmsg_level == SOL_SOCKET
1574 && cm->cmsg_type == SCM_RIGHTS) {
1575 newfds = datalen / sizeof(struct file *);
1576 rp = data;
1577
1578 /* If we're not outputting the descriptors free them. */
1579 if (error || controlp == NULL) {
1580 unp_freerights(rp, newfds);
1581 goto next;
1582 }
1583 FILEDESC_XLOCK(td->td_proc->p_fd);
1584 /* if the new FD's will not fit free them. */
1585 if (!fdavail(td, newfds)) {
1586 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1587 error = EMSGSIZE;
1588 unp_freerights(rp, newfds);
1589 goto next;
1590 }
1591
1592 /*
1593 * Now change each pointer to an fd in the global
1594 * table to an integer that is the index to the local
1595 * fd table entry that we set up to point to the
1596 * global one we are transferring.
1597 */
1598 newlen = newfds * sizeof(int);
1599 *controlp = sbcreatecontrol(NULL, newlen,
1600 SCM_RIGHTS, SOL_SOCKET);
1601 if (*controlp == NULL) {
1602 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1603 error = E2BIG;
1604 unp_freerights(rp, newfds);
1605 goto next;
1606 }
1607
1608 fdp = (int *)
1609 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1610 for (i = 0; i < newfds; i++) {
1611 if (fdalloc(td, 0, &f))
1612 panic("unp_externalize fdalloc failed");
1613 fp = *rp++;
1614 td->td_proc->p_fd->fd_ofiles[f] = fp;
1615 FILE_LOCK(fp);
1616 fp->f_msgcount--;
1617 FILE_UNLOCK(fp);
1618 UNP_GLOBAL_WLOCK();
1619 unp_rights--;
1620 UNP_GLOBAL_WUNLOCK();
1621 *fdp++ = f;
1622 }
1623 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1624 } else {
1625 /* We can just copy anything else across. */
1626 if (error || controlp == NULL)
1627 goto next;
1628 *controlp = sbcreatecontrol(NULL, datalen,
1629 cm->cmsg_type, cm->cmsg_level);
1630 if (*controlp == NULL) {
1631 error = ENOBUFS;
1632 goto next;
1633 }
1634 bcopy(data,
1635 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
1636 datalen);
1637 }
1638 controlp = &(*controlp)->m_next;
1639
1640 next:
1641 if (CMSG_SPACE(datalen) < clen) {
1642 clen -= CMSG_SPACE(datalen);
1643 cm = (struct cmsghdr *)
1644 ((caddr_t)cm + CMSG_SPACE(datalen));
1645 } else {
1646 clen = 0;
1647 cm = NULL;
1648 }
1649 }
1650
1651 m_freem(control);
1652 return (error);
1653 }
1654
1655 static void
1656 unp_zone_change(void *tag)
1657 {
1658
1659 uma_zone_set_max(unp_zone, maxsockets);
1660 }
1661
1662 static void
1663 unp_init(void)
1664 {
1665
1666 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
1667 NULL, NULL, UMA_ALIGN_PTR, 0);
1668 if (unp_zone == NULL)
1669 panic("unp_init");
1670 uma_zone_set_max(unp_zone, maxsockets);
1671 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
1672 NULL, EVENTHANDLER_PRI_ANY);
1673 LIST_INIT(&unp_dhead);
1674 LIST_INIT(&unp_shead);
1675 TASK_INIT(&unp_gc_task, 0, unp_gc, NULL);
1676 UNP_GLOBAL_LOCK_INIT();
1677 }
1678
1679 static int
1680 unp_internalize(struct mbuf **controlp, struct thread *td)
1681 {
1682 struct mbuf *control = *controlp;
1683 struct proc *p = td->td_proc;
1684 struct filedesc *fdescp = p->p_fd;
1685 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1686 struct cmsgcred *cmcred;
1687 struct file **rp;
1688 struct file *fp;
1689 struct timeval *tv;
1690 int i, fd, *fdp;
1691 void *data;
1692 socklen_t clen = control->m_len, datalen;
1693 int error, oldfds;
1694 u_int newlen;
1695
1696 UNP_GLOBAL_UNLOCK_ASSERT();
1697
1698 error = 0;
1699 *controlp = NULL;
1700 while (cm != NULL) {
1701 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
1702 || cm->cmsg_len > clen) {
1703 error = EINVAL;
1704 goto out;
1705 }
1706 data = CMSG_DATA(cm);
1707 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1708
1709 switch (cm->cmsg_type) {
1710 /*
1711 * Fill in credential information.
1712 */
1713 case SCM_CREDS:
1714 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
1715 SCM_CREDS, SOL_SOCKET);
1716 if (*controlp == NULL) {
1717 error = ENOBUFS;
1718 goto out;
1719 }
1720 cmcred = (struct cmsgcred *)
1721 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1722 cmcred->cmcred_pid = p->p_pid;
1723 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
1724 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
1725 cmcred->cmcred_euid = td->td_ucred->cr_uid;
1726 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
1727 CMGROUP_MAX);
1728 for (i = 0; i < cmcred->cmcred_ngroups; i++)
1729 cmcred->cmcred_groups[i] =
1730 td->td_ucred->cr_groups[i];
1731 break;
1732
1733 case SCM_RIGHTS:
1734 oldfds = datalen / sizeof (int);
1735 /*
1736 * Check that all the FDs passed in refer to legal
1737 * files. If not, reject the entire operation.
1738 */
1739 fdp = data;
1740 FILEDESC_SLOCK(fdescp);
1741 for (i = 0; i < oldfds; i++) {
1742 fd = *fdp++;
1743 if ((unsigned)fd >= fdescp->fd_nfiles ||
1744 fdescp->fd_ofiles[fd] == NULL) {
1745 FILEDESC_SUNLOCK(fdescp);
1746 error = EBADF;
1747 goto out;
1748 }
1749 fp = fdescp->fd_ofiles[fd];
1750 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
1751 FILEDESC_SUNLOCK(fdescp);
1752 error = EOPNOTSUPP;
1753 goto out;
1754 }
1755
1756 }
1757
1758 /*
1759 * Now replace the integer FDs with pointers to the
1760 * associated global file table entry..
1761 */
1762 newlen = oldfds * sizeof(struct file *);
1763 *controlp = sbcreatecontrol(NULL, newlen,
1764 SCM_RIGHTS, SOL_SOCKET);
1765 if (*controlp == NULL) {
1766 FILEDESC_SUNLOCK(fdescp);
1767 error = E2BIG;
1768 goto out;
1769 }
1770 fdp = data;
1771 rp = (struct file **)
1772 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1773 for (i = 0; i < oldfds; i++) {
1774 fp = fdescp->fd_ofiles[*fdp++];
1775 *rp++ = fp;
1776 FILE_LOCK(fp);
1777 fp->f_count++;
1778 fp->f_msgcount++;
1779 FILE_UNLOCK(fp);
1780 UNP_GLOBAL_WLOCK();
1781 unp_rights++;
1782 UNP_GLOBAL_WUNLOCK();
1783 }
1784 FILEDESC_SUNLOCK(fdescp);
1785 break;
1786
1787 case SCM_TIMESTAMP:
1788 *controlp = sbcreatecontrol(NULL, sizeof(*tv),
1789 SCM_TIMESTAMP, SOL_SOCKET);
1790 if (*controlp == NULL) {
1791 error = ENOBUFS;
1792 goto out;
1793 }
1794 tv = (struct timeval *)
1795 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1796 microtime(tv);
1797 break;
1798
1799 default:
1800 error = EINVAL;
1801 goto out;
1802 }
1803
1804 controlp = &(*controlp)->m_next;
1805 if (CMSG_SPACE(datalen) < clen) {
1806 clen -= CMSG_SPACE(datalen);
1807 cm = (struct cmsghdr *)
1808 ((caddr_t)cm + CMSG_SPACE(datalen));
1809 } else {
1810 clen = 0;
1811 cm = NULL;
1812 }
1813 }
1814
1815 out:
1816 m_freem(control);
1817 return (error);
1818 }
1819
1820 static struct mbuf *
1821 unp_addsockcred(struct thread *td, struct mbuf *control)
1822 {
1823 struct mbuf *m, *n, *n_prev;
1824 struct sockcred *sc;
1825 const struct cmsghdr *cm;
1826 int ngroups;
1827 int i;
1828
1829 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
1830 m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
1831 if (m == NULL)
1832 return (control);
1833
1834 sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
1835 sc->sc_uid = td->td_ucred->cr_ruid;
1836 sc->sc_euid = td->td_ucred->cr_uid;
1837 sc->sc_gid = td->td_ucred->cr_rgid;
1838 sc->sc_egid = td->td_ucred->cr_gid;
1839 sc->sc_ngroups = ngroups;
1840 for (i = 0; i < sc->sc_ngroups; i++)
1841 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
1842
1843 /*
1844 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
1845 * created SCM_CREDS control message (struct sockcred) has another
1846 * format.
1847 */
1848 if (control != NULL)
1849 for (n = control, n_prev = NULL; n != NULL;) {
1850 cm = mtod(n, struct cmsghdr *);
1851 if (cm->cmsg_level == SOL_SOCKET &&
1852 cm->cmsg_type == SCM_CREDS) {
1853 if (n_prev == NULL)
1854 control = n->m_next;
1855 else
1856 n_prev->m_next = n->m_next;
1857 n = m_free(n);
1858 } else {
1859 n_prev = n;
1860 n = n->m_next;
1861 }
1862 }
1863
1864 /* Prepend it to the head. */
1865 m->m_next = control;
1866 return (m);
1867 }
1868
1869 /*
1870 * unp_defer indicates whether additional work has been defered for a future
1871 * pass through unp_gc(). It is thread local and does not require explicit
1872 * synchronization.
1873 */
1874 static int unp_defer;
1875
1876 static int unp_taskcount;
1877 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0, "");
1878
1879 static int unp_recycled;
1880 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0, "");
1881
1882 static void
1883 unp_gc(__unused void *arg, int pending)
1884 {
1885 struct file *fp, *nextfp;
1886 struct socket *so;
1887 struct socket *soa;
1888 struct file **extra_ref, **fpp;
1889 int nunref, i;
1890 int nfiles_snap;
1891 int nfiles_slack = 20;
1892
1893 unp_taskcount++;
1894 unp_defer = 0;
1895
1896 /*
1897 * Before going through all this, set all FDs to be NOT deferred and
1898 * NOT externally accessible.
1899 */
1900 sx_slock(&filelist_lock);
1901 LIST_FOREACH(fp, &filehead, f_list)
1902 fp->f_gcflag &= ~(FMARK|FDEFER);
1903 do {
1904 KASSERT(unp_defer >= 0, ("unp_gc: unp_defer %d", unp_defer));
1905 LIST_FOREACH(fp, &filehead, f_list) {
1906 FILE_LOCK(fp);
1907 /*
1908 * If the file is not open, skip it -- could be a
1909 * file in the process of being opened, or in the
1910 * process of being closed. If the file is
1911 * "closing", it may have been marked for deferred
1912 * consideration. Clear the flag now if so.
1913 */
1914 if (fp->f_count == 0) {
1915 if (fp->f_gcflag & FDEFER)
1916 unp_defer--;
1917 fp->f_gcflag &= ~(FMARK|FDEFER);
1918 FILE_UNLOCK(fp);
1919 continue;
1920 }
1921
1922 /*
1923 * If we already marked it as 'defer' in a
1924 * previous pass, then try to process it this
1925 * time and un-mark it.
1926 */
1927 if (fp->f_gcflag & FDEFER) {
1928 fp->f_gcflag &= ~FDEFER;
1929 unp_defer--;
1930 } else {
1931 /*
1932 * If it's not deferred, then check if it's
1933 * already marked.. if so skip it
1934 */
1935 if (fp->f_gcflag & FMARK) {
1936 FILE_UNLOCK(fp);
1937 continue;
1938 }
1939
1940 /*
1941 * If all references are from messages in
1942 * transit, then skip it. it's not externally
1943 * accessible.
1944 */
1945 if (fp->f_count == fp->f_msgcount) {
1946 FILE_UNLOCK(fp);
1947 continue;
1948 }
1949
1950 /*
1951 * If it got this far then it must be
1952 * externally accessible.
1953 */
1954 fp->f_gcflag |= FMARK;
1955 }
1956
1957 /*
1958 * Either it was deferred, or it is externally
1959 * accessible and not already marked so. Now check
1960 * if it is possibly one of OUR sockets.
1961 */
1962 if (fp->f_type != DTYPE_SOCKET ||
1963 (so = fp->f_data) == NULL) {
1964 FILE_UNLOCK(fp);
1965 continue;
1966 }
1967
1968 if (so->so_proto->pr_domain != &localdomain ||
1969 (so->so_proto->pr_flags & PR_RIGHTS) == 0) {
1970 FILE_UNLOCK(fp);
1971 continue;
1972 }
1973
1974 /*
1975 * Tell any other threads that do a subsequent
1976 * fdrop() that we are scanning the message
1977 * buffers.
1978 */
1979 fp->f_gcflag |= FWAIT;
1980 FILE_UNLOCK(fp);
1981
1982 /*
1983 * So, Ok, it's one of our sockets and it IS
1984 * externally accessible (or was deferred). Now we
1985 * look to see if we hold any file descriptors in its
1986 * message buffers. Follow those links and mark them
1987 * as accessible too.
1988 */
1989 SOCKBUF_LOCK(&so->so_rcv);
1990 unp_scan(so->so_rcv.sb_mb, unp_mark);
1991 SOCKBUF_UNLOCK(&so->so_rcv);
1992
1993 /*
1994 * If socket is in listening state, then sockets
1995 * in its accept queue are accessible, and so
1996 * are any descriptors in those sockets' receive
1997 * queues.
1998 */
1999 ACCEPT_LOCK();
2000 TAILQ_FOREACH(soa, &so->so_comp, so_list) {
2001 SOCKBUF_LOCK(&soa->so_rcv);
2002 unp_scan(soa->so_rcv.sb_mb, unp_mark);
2003 SOCKBUF_UNLOCK(&soa->so_rcv);
2004 }
2005 ACCEPT_UNLOCK();
2006
2007 /*
2008 * Wake up any threads waiting in fdrop().
2009 */
2010 FILE_LOCK(fp);
2011 fp->f_gcflag &= ~FWAIT;
2012 wakeup(&fp->f_gcflag);
2013 FILE_UNLOCK(fp);
2014 }
2015 } while (unp_defer);
2016 sx_sunlock(&filelist_lock);
2017
2018 /*
2019 * XXXRW: The following comments need updating for a post-SMPng and
2020 * deferred unp_gc() world, but are still generally accurate.
2021 *
2022 * We grab an extra reference to each of the file table entries that
2023 * are not otherwise accessible and then free the rights that are
2024 * stored in messages on them.
2025 *
2026 * The bug in the orginal code is a little tricky, so I'll describe
2027 * what's wrong with it here.
2028 *
2029 * It is incorrect to simply unp_discard each entry for f_msgcount
2030 * times -- consider the case of sockets A and B that contain
2031 * references to each other. On a last close of some other socket,
2032 * we trigger a gc since the number of outstanding rights (unp_rights)
2033 * is non-zero. If during the sweep phase the gc code unp_discards,
2034 * we end up doing a (full) closef on the descriptor. A closef on A
2035 * results in the following chain. Closef calls soo_close, which
2036 * calls soclose. Soclose calls first (through the switch
2037 * uipc_usrreq) unp_detach, which re-invokes unp_gc. Unp_gc simply
2038 * returns because the previous instance had set unp_gcing, and we
2039 * return all the way back to soclose, which marks the socket with
2040 * SS_NOFDREF, and then calls sofree. Sofree calls sorflush to free
2041 * up the rights that are queued in messages on the socket A, i.e.,
2042 * the reference on B. The sorflush calls via the dom_dispose switch
2043 * unp_dispose, which unp_scans with unp_discard. This second
2044 * instance of unp_discard just calls closef on B.
2045 *
2046 * Well, a similar chain occurs on B, resulting in a sorflush on B,
2047 * which results in another closef on A. Unfortunately, A is already
2048 * being closed, and the descriptor has already been marked with
2049 * SS_NOFDREF, and soclose panics at this point.
2050 *
2051 * Here, we first take an extra reference to each inaccessible
2052 * descriptor. Then, we call sorflush ourself, since we know it is a
2053 * Unix domain socket anyhow. After we destroy all the rights
2054 * carried in messages, we do a last closef to get rid of our extra
2055 * reference. This is the last close, and the unp_detach etc will
2056 * shut down the socket.
2057 *
2058 * 91/09/19, bsy@cs.cmu.edu
2059 */
2060 again:
2061 nfiles_snap = openfiles + nfiles_slack; /* some slack */
2062 extra_ref = malloc(nfiles_snap * sizeof(struct file *), M_TEMP,
2063 M_WAITOK);
2064 sx_slock(&filelist_lock);
2065 if (nfiles_snap < openfiles) {
2066 sx_sunlock(&filelist_lock);
2067 free(extra_ref, M_TEMP);
2068 nfiles_slack += 20;
2069 goto again;
2070 }
2071 for (nunref = 0, fp = LIST_FIRST(&filehead), fpp = extra_ref;
2072 fp != NULL; fp = nextfp) {
2073 nextfp = LIST_NEXT(fp, f_list);
2074 FILE_LOCK(fp);
2075
2076 /*
2077 * If it's not open, skip it
2078 */
2079 if (fp->f_count == 0) {
2080 FILE_UNLOCK(fp);
2081 continue;
2082 }
2083
2084 /*
2085 * If all refs are from msgs, and it's not marked accessible
2086 * then it must be referenced from some unreachable cycle of
2087 * (shut-down) FDs, so include it in our list of FDs to
2088 * remove.
2089 */
2090 if (fp->f_count == fp->f_msgcount && !(fp->f_gcflag & FMARK)) {
2091 *fpp++ = fp;
2092 nunref++;
2093 fp->f_count++;
2094 }
2095 FILE_UNLOCK(fp);
2096 }
2097 sx_sunlock(&filelist_lock);
2098
2099 /*
2100 * For each FD on our hit list, do the following two things:
2101 */
2102 for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
2103 struct file *tfp = *fpp;
2104 FILE_LOCK(tfp);
2105 if (tfp->f_type == DTYPE_SOCKET &&
2106 tfp->f_data != NULL) {
2107 FILE_UNLOCK(tfp);
2108 sorflush(tfp->f_data);
2109 } else {
2110 FILE_UNLOCK(tfp);
2111 }
2112 }
2113 for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
2114 closef(*fpp, (struct thread *) NULL);
2115 unp_recycled++;
2116 }
2117 free(extra_ref, M_TEMP);
2118 }
2119
2120 static void
2121 unp_dispose(struct mbuf *m)
2122 {
2123
2124 if (m)
2125 unp_scan(m, unp_discard);
2126 }
2127
2128 static void
2129 unp_scan(struct mbuf *m0, void (*op)(struct file *))
2130 {
2131 struct mbuf *m;
2132 struct file **rp;
2133 struct cmsghdr *cm;
2134 void *data;
2135 int i;
2136 socklen_t clen, datalen;
2137 int qfds;
2138
2139 while (m0 != NULL) {
2140 for (m = m0; m; m = m->m_next) {
2141 if (m->m_type != MT_CONTROL)
2142 continue;
2143
2144 cm = mtod(m, struct cmsghdr *);
2145 clen = m->m_len;
2146
2147 while (cm != NULL) {
2148 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2149 break;
2150
2151 data = CMSG_DATA(cm);
2152 datalen = (caddr_t)cm + cm->cmsg_len
2153 - (caddr_t)data;
2154
2155 if (cm->cmsg_level == SOL_SOCKET &&
2156 cm->cmsg_type == SCM_RIGHTS) {
2157 qfds = datalen / sizeof (struct file *);
2158 rp = data;
2159 for (i = 0; i < qfds; i++)
2160 (*op)(*rp++);
2161 }
2162
2163 if (CMSG_SPACE(datalen) < clen) {
2164 clen -= CMSG_SPACE(datalen);
2165 cm = (struct cmsghdr *)
2166 ((caddr_t)cm + CMSG_SPACE(datalen));
2167 } else {
2168 clen = 0;
2169 cm = NULL;
2170 }
2171 }
2172 }
2173 m0 = m0->m_act;
2174 }
2175 }
2176
2177 static void
2178 unp_mark(struct file *fp)
2179 {
2180
2181 /* XXXRW: Should probably assert file list lock here. */
2182
2183 if (fp->f_gcflag & FMARK)
2184 return;
2185 unp_defer++;
2186 fp->f_gcflag |= (FMARK|FDEFER);
2187 }
2188
2189 static void
2190 unp_discard(struct file *fp)
2191 {
2192
2193 UNP_GLOBAL_WLOCK();
2194 FILE_LOCK(fp);
2195 fp->f_msgcount--;
2196 unp_rights--;
2197 FILE_UNLOCK(fp);
2198 UNP_GLOBAL_WUNLOCK();
2199 (void) closef(fp, (struct thread *)NULL);
2200 }
2201
2202 #ifdef DDB
2203 static void
2204 db_print_indent(int indent)
2205 {
2206 int i;
2207
2208 for (i = 0; i < indent; i++)
2209 db_printf(" ");
2210 }
2211
2212 static void
2213 db_print_unpflags(int unp_flags)
2214 {
2215 int comma;
2216
2217 comma = 0;
2218 if (unp_flags & UNP_HAVEPC) {
2219 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
2220 comma = 1;
2221 }
2222 if (unp_flags & UNP_HAVEPCCACHED) {
2223 db_printf("%sUNP_HAVEPCCACHED", comma ? ", " : "");
2224 comma = 1;
2225 }
2226 if (unp_flags & UNP_WANTCRED) {
2227 db_printf("%sUNP_WANTCRED", comma ? ", " : "");
2228 comma = 1;
2229 }
2230 if (unp_flags & UNP_CONNWAIT) {
2231 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
2232 comma = 1;
2233 }
2234 if (unp_flags & UNP_CONNECTING) {
2235 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
2236 comma = 1;
2237 }
2238 if (unp_flags & UNP_BINDING) {
2239 db_printf("%sUNP_BINDING", comma ? ", " : "");
2240 comma = 1;
2241 }
2242 }
2243
2244 static void
2245 db_print_xucred(int indent, struct xucred *xu)
2246 {
2247 int comma, i;
2248
2249 db_print_indent(indent);
2250 db_printf("cr_version: %u cr_uid: %u cr_ngroups: %d\n",
2251 xu->cr_version, xu->cr_uid, xu->cr_ngroups);
2252 db_print_indent(indent);
2253 db_printf("cr_groups: ");
2254 comma = 0;
2255 for (i = 0; i < xu->cr_ngroups; i++) {
2256 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
2257 comma = 1;
2258 }
2259 db_printf("\n");
2260 }
2261
2262 static void
2263 db_print_unprefs(int indent, struct unp_head *uh)
2264 {
2265 struct unpcb *unp;
2266 int counter;
2267
2268 counter = 0;
2269 LIST_FOREACH(unp, uh, unp_reflink) {
2270 if (counter % 4 == 0)
2271 db_print_indent(indent);
2272 db_printf("%p ", unp);
2273 if (counter % 4 == 3)
2274 db_printf("\n");
2275 counter++;
2276 }
2277 if (counter != 0 && counter % 4 != 0)
2278 db_printf("\n");
2279 }
2280
2281 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
2282 {
2283 struct unpcb *unp;
2284
2285 if (!have_addr) {
2286 db_printf("usage: show unpcb <addr>\n");
2287 return;
2288 }
2289 unp = (struct unpcb *)addr;
2290
2291 db_printf("unp_socket: %p unp_vnode: %p\n", unp->unp_socket,
2292 unp->unp_vnode);
2293
2294 db_printf("unp_ino: %d unp_conn: %p\n", unp->unp_ino,
2295 unp->unp_conn);
2296
2297 db_printf("unp_refs:\n");
2298 db_print_unprefs(2, &unp->unp_refs);
2299
2300 /* XXXRW: Would be nice to print the full address, if any. */
2301 db_printf("unp_addr: %p\n", unp->unp_addr);
2302
2303 db_printf("unp_cc: %d unp_mbcnt: %d unp_gencnt: %llu\n",
2304 unp->unp_cc, unp->unp_mbcnt,
2305 (unsigned long long)unp->unp_gencnt);
2306
2307 db_printf("unp_flags: %x (", unp->unp_flags);
2308 db_print_unpflags(unp->unp_flags);
2309 db_printf(")\n");
2310
2311 db_printf("unp_peercred:\n");
2312 db_print_xucred(2, &unp->unp_peercred);
2313
2314 db_printf("unp_refcount: %u\n", unp->unp_refcount);
2315 }
2316 #endif
Cache object: ec935612905543fdd82fc8207c0d4950
|