]> git.saurik.com Git - apple/xnu.git/blob - bsd/kern/uipc_usrreq.c
07f56acbdb6674202f316a170ef68b53bb50c79e
[apple/xnu.git] / bsd / kern / uipc_usrreq.c
1 /*
2 * Copyright (c) 2000-2004 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23 /*
24 * Copyright (c) 1982, 1986, 1989, 1991, 1993
25 * The Regents of the University of California. All rights reserved.
26 *
27 * Redistribution and use in source and binary forms, with or without
28 * modification, are permitted provided that the following conditions
29 * are met:
30 * 1. Redistributions of source code must retain the above copyright
31 * notice, this list of conditions and the following disclaimer.
32 * 2. Redistributions in binary form must reproduce the above copyright
33 * notice, this list of conditions and the following disclaimer in the
34 * documentation and/or other materials provided with the distribution.
35 * 3. All advertising materials mentioning features or use of this software
36 * must display the following acknowledgement:
37 * This product includes software developed by the University of
38 * California, Berkeley and its contributors.
39 * 4. Neither the name of the University nor the names of its contributors
40 * may be used to endorse or promote products derived from this software
41 * without specific prior written permission.
42 *
43 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
44 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
45 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
46 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
47 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
48 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
49 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
51 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
52 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53 * SUCH DAMAGE.
54 *
55 * From: @(#)uipc_usrreq.c 8.3 (Berkeley) 1/4/94
56 */
57
58 #include <sys/param.h>
59 #include <sys/systm.h>
60 #include <sys/kernel.h>
61 #include <sys/domain.h>
62 #include <sys/fcntl.h>
63 #include <sys/malloc.h> /* XXX must be before <sys/file.h> */
64 #include <sys/file_internal.h>
65 #include <sys/filedesc.h>
66 #include <sys/lock.h>
67 #include <sys/mbuf.h>
68 #include <sys/namei.h>
69 #include <sys/proc_internal.h>
70 #include <sys/kauth.h>
71 #include <sys/protosw.h>
72 #include <sys/socket.h>
73 #include <sys/socketvar.h>
74 #include <sys/stat.h>
75 #include <sys/sysctl.h>
76 #include <sys/un.h>
77 #include <sys/unpcb.h>
78 #include <sys/vnode_internal.h>
79 #include <sys/kdebug.h>
80
81 #include <kern/zalloc.h>
82 #include <kern/locks.h>
83
84 #define f_msgcount f_fglob->fg_msgcount
85 #define f_cred f_fglob->fg_cred
86 #define f_ops f_fglob->fg_ops
87 #define f_offset f_fglob->fg_offset
88 #define f_data f_fglob->fg_data
89 struct zone *unp_zone;
90 static unp_gen_t unp_gencnt;
91 static u_int unp_count;
92 static lck_mtx_t *unp_mutex;
93
94 extern lck_mtx_t * uipc_lock;
95 static struct unp_head unp_shead, unp_dhead;
96
97 /*
98 * Unix communications domain.
99 *
100 * TODO:
101 * SEQPACKET, RDM
102 * rethink name space problems
103 * need a proper out-of-band
104 * lock pushdown
105 */
106 static struct sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL, { 0 } };
107 static ino_t unp_ino; /* prototype for fake inode numbers */
108
109 static int unp_attach(struct socket *);
110 static void unp_detach(struct unpcb *);
111 static int unp_bind(struct unpcb *,struct sockaddr *, struct proc *);
112 static int unp_connect(struct socket *,struct sockaddr *, struct proc *);
113 static void unp_disconnect(struct unpcb *);
114 static void unp_shutdown(struct unpcb *);
115 static void unp_drop(struct unpcb *, int);
116 static void unp_gc(void);
117 static void unp_scan(struct mbuf *, void (*)(struct fileglob *));
118 static void unp_mark(struct fileglob *);
119 static void unp_discard(struct fileglob *);
120 static void unp_discard_fdlocked(struct fileglob *, struct proc *);
121 static int unp_internalize(struct mbuf *, struct proc *);
122 static int unp_listen(struct unpcb *, struct proc *);
123
124
125 static int
126 uipc_abort(struct socket *so)
127 {
128 struct unpcb *unp = sotounpcb(so);
129
130 if (unp == 0)
131 return EINVAL;
132 unp_drop(unp, ECONNABORTED);
133 unp_detach(unp);
134 sofree(so);
135 return 0;
136 }
137
138 static int
139 uipc_accept(struct socket *so, struct sockaddr **nam)
140 {
141 struct unpcb *unp = sotounpcb(so);
142
143 if (unp == 0)
144 return EINVAL;
145
146 /*
147 * Pass back name of connected socket,
148 * if it was bound and we are still connected
149 * (our peer may have closed already!).
150 */
151 if (unp->unp_conn && unp->unp_conn->unp_addr) {
152 *nam = dup_sockaddr((struct sockaddr *)unp->unp_conn->unp_addr,
153 1);
154 } else {
155 *nam = dup_sockaddr((struct sockaddr *)&sun_noname, 1);
156 }
157 return 0;
158 }
159
160 static int
161 uipc_attach(struct socket *so, __unused int proto, __unused struct proc *p)
162 {
163 struct unpcb *unp = sotounpcb(so);
164
165 if (unp != 0)
166 return EISCONN;
167 return unp_attach(so);
168 }
169
170 static int
171 uipc_bind(struct socket *so, struct sockaddr *nam, struct proc *p)
172 {
173 struct unpcb *unp = sotounpcb(so);
174
175 if (unp == 0)
176 return EINVAL;
177
178 return unp_bind(unp, nam, p);
179 }
180
181 static int
182 uipc_connect(struct socket *so, struct sockaddr *nam, struct proc *p)
183 {
184 struct unpcb *unp = sotounpcb(so);
185
186 if (unp == 0)
187 return EINVAL;
188 return unp_connect(so, nam, p);
189 }
190
191 static int
192 uipc_connect2(struct socket *so1, struct socket *so2)
193 {
194 struct unpcb *unp = sotounpcb(so1);
195
196 if (unp == 0)
197 return EINVAL;
198
199 return unp_connect2(so1, so2);
200 }
201
202 /* control is EOPNOTSUPP */
203
204 static int
205 uipc_detach(struct socket *so)
206 {
207 struct unpcb *unp = sotounpcb(so);
208
209 if (unp == 0)
210 return EINVAL;
211
212 unp_detach(unp);
213 return 0;
214 }
215
216 static int
217 uipc_disconnect(struct socket *so)
218 {
219 struct unpcb *unp = sotounpcb(so);
220
221 if (unp == 0)
222 return EINVAL;
223 unp_disconnect(unp);
224 return 0;
225 }
226
227 static int
228 uipc_listen(struct socket *so, __unused struct proc *p)
229 {
230 struct unpcb *unp = sotounpcb(so);
231
232 if (unp == 0 || unp->unp_vnode == 0)
233 return EINVAL;
234 return unp_listen(unp, p);
235 }
236
237 static int
238 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
239 {
240 struct unpcb *unp = sotounpcb(so);
241
242 if (unp == 0)
243 return EINVAL;
244 if (unp->unp_conn && unp->unp_conn->unp_addr)
245 *nam = dup_sockaddr((struct sockaddr *)unp->unp_conn->unp_addr,
246 1);
247 return 0;
248 }
249
250 static int
251 uipc_rcvd(struct socket *so, __unused int flags)
252 {
253 struct unpcb *unp = sotounpcb(so);
254 struct socket *so2;
255
256 if (unp == 0)
257 return EINVAL;
258 switch (so->so_type) {
259 case SOCK_DGRAM:
260 panic("uipc_rcvd DGRAM?");
261 /*NOTREACHED*/
262
263 case SOCK_STREAM:
264 #define rcv (&so->so_rcv)
265 #define snd (&so2->so_snd)
266 if (unp->unp_conn == 0)
267 break;
268 so2 = unp->unp_conn->unp_socket;
269 /*
270 * Adjust backpressure on sender
271 * and wakeup any waiting to write.
272 */
273 snd->sb_mbmax += unp->unp_mbcnt - rcv->sb_mbcnt;
274 unp->unp_mbcnt = rcv->sb_mbcnt;
275 snd->sb_hiwat += unp->unp_cc - rcv->sb_cc;
276 unp->unp_cc = rcv->sb_cc;
277 sowwakeup(so2);
278 #undef snd
279 #undef rcv
280 break;
281
282 default:
283 panic("uipc_rcvd unknown socktype");
284 }
285 return 0;
286 }
287
288 /* pru_rcvoob is EOPNOTSUPP */
289
290 static int
291 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
292 struct mbuf *control, struct proc *p)
293 {
294 int error = 0;
295 struct unpcb *unp = sotounpcb(so);
296 struct socket *so2;
297
298 if (unp == 0) {
299 error = EINVAL;
300 goto release;
301 }
302 if (flags & PRUS_OOB) {
303 error = EOPNOTSUPP;
304 goto release;
305 }
306
307 if (control && (error = unp_internalize(control, p)))
308 goto release;
309
310 switch (so->so_type) {
311 case SOCK_DGRAM:
312 {
313 struct sockaddr *from;
314
315 if (nam) {
316 if (unp->unp_conn) {
317 error = EISCONN;
318 break;
319 }
320 error = unp_connect(so, nam, p);
321 if (error)
322 break;
323 } else {
324 if (unp->unp_conn == 0) {
325 error = ENOTCONN;
326 break;
327 }
328 }
329 so2 = unp->unp_conn->unp_socket;
330 if (unp->unp_addr)
331 from = (struct sockaddr *)unp->unp_addr;
332 else
333 from = &sun_noname;
334 if (sbappendaddr(&so2->so_rcv, from, m, control, &error)) {
335 sorwakeup(so2);
336 }
337 m = 0;
338 control = 0;
339 if (nam)
340 unp_disconnect(unp);
341 break;
342 }
343
344 case SOCK_STREAM: {
345 int didreceive = 0;
346 #define rcv (&so2->so_rcv)
347 #define snd (&so->so_snd)
348 /* Connect if not connected yet. */
349 /*
350 * Note: A better implementation would complain
351 * if not equal to the peer's address.
352 */
353 if ((so->so_state & SS_ISCONNECTED) == 0) {
354 if (nam) {
355 error = unp_connect(so, nam, p);
356 if (error)
357 break; /* XXX */
358 } else {
359 error = ENOTCONN;
360 break;
361 }
362 }
363
364 if (so->so_state & SS_CANTSENDMORE) {
365 error = EPIPE;
366 break;
367 }
368 if (unp->unp_conn == 0)
369 panic("uipc_send connected but no connection?");
370 so2 = unp->unp_conn->unp_socket;
371 /*
372 * Send to paired receive port, and then reduce
373 * send buffer hiwater marks to maintain backpressure.
374 * Wake up readers.
375 */
376 if ((control && sbappendcontrol(rcv, m, control, NULL)) ||
377 sbappend(rcv, m)) {
378 didreceive = 1;
379 }
380 snd->sb_mbmax -=
381 rcv->sb_mbcnt - unp->unp_conn->unp_mbcnt;
382 unp->unp_conn->unp_mbcnt = rcv->sb_mbcnt;
383 snd->sb_hiwat -= rcv->sb_cc - unp->unp_conn->unp_cc;
384 unp->unp_conn->unp_cc = rcv->sb_cc;
385 if (didreceive)
386 sorwakeup(so2);
387 m = 0;
388 control = 0;
389 #undef snd
390 #undef rcv
391 }
392 break;
393
394 default:
395 panic("uipc_send unknown socktype");
396 }
397
398 /*
399 * SEND_EOF is equivalent to a SEND followed by
400 * a SHUTDOWN.
401 */
402 if (flags & PRUS_EOF) {
403 socantsendmore(so);
404 unp_shutdown(unp);
405 }
406
407 if (control && error != 0)
408 unp_dispose(control);
409
410 release:
411 if (control)
412 m_freem(control);
413 if (m)
414 m_freem(m);
415 return error;
416 }
417
418 static int
419 uipc_sense(struct socket *so, struct stat *sb)
420 {
421 struct unpcb *unp = sotounpcb(so);
422 struct socket *so2;
423
424 if (unp == 0)
425 return EINVAL;
426 sb->st_blksize = so->so_snd.sb_hiwat;
427 if (so->so_type == SOCK_STREAM && unp->unp_conn != 0) {
428 so2 = unp->unp_conn->unp_socket;
429 sb->st_blksize += so2->so_rcv.sb_cc;
430 }
431 sb->st_dev = NODEV;
432 if (unp->unp_ino == 0)
433 unp->unp_ino = unp_ino++;
434 sb->st_ino = unp->unp_ino;
435 return (0);
436 }
437
438 static int
439 uipc_shutdown(struct socket *so)
440 {
441 struct unpcb *unp = sotounpcb(so);
442
443 if (unp == 0)
444 return EINVAL;
445 socantsendmore(so);
446 unp_shutdown(unp);
447 return 0;
448 }
449
450 static int
451 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
452 {
453 struct unpcb *unp = sotounpcb(so);
454
455 if (unp == 0)
456 return EINVAL;
457 if (unp->unp_addr)
458 *nam = dup_sockaddr((struct sockaddr *)unp->unp_addr, 1);
459 return 0;
460 }
461
462 struct pr_usrreqs uipc_usrreqs = {
463 uipc_abort, uipc_accept, uipc_attach, uipc_bind, uipc_connect,
464 uipc_connect2, pru_control_notsupp, uipc_detach, uipc_disconnect,
465 uipc_listen, uipc_peeraddr, uipc_rcvd, pru_rcvoob_notsupp,
466 uipc_send, uipc_sense, uipc_shutdown, uipc_sockaddr,
467 sosend, soreceive, pru_sopoll_notsupp
468 };
469
470 int
471 uipc_ctloutput(
472 struct socket *so,
473 struct sockopt *sopt)
474 {
475 struct unpcb *unp = sotounpcb(so);
476 int error;
477
478 switch (sopt->sopt_dir) {
479 case SOPT_GET:
480 switch (sopt->sopt_name) {
481 case LOCAL_PEERCRED:
482 if (unp->unp_flags & UNP_HAVEPC)
483 error = sooptcopyout(sopt, &unp->unp_peercred,
484 sizeof(unp->unp_peercred));
485 else {
486 if (so->so_type == SOCK_STREAM)
487 error = ENOTCONN;
488 else
489 error = EINVAL;
490 }
491 break;
492 default:
493 error = EOPNOTSUPP;
494 break;
495 }
496 break;
497 case SOPT_SET:
498 default:
499 error = EOPNOTSUPP;
500 break;
501 }
502 return (error);
503 }
504
505 /*
506 * Both send and receive buffers are allocated PIPSIZ bytes of buffering
507 * for stream sockets, although the total for sender and receiver is
508 * actually only PIPSIZ.
509 * Datagram sockets really use the sendspace as the maximum datagram size,
510 * and don't really want to reserve the sendspace. Their recvspace should
511 * be large enough for at least one max-size datagram plus address.
512 */
513 #ifndef PIPSIZ
514 #define PIPSIZ 8192
515 #endif
516 static u_long unpst_sendspace = PIPSIZ;
517 static u_long unpst_recvspace = PIPSIZ;
518 static u_long unpdg_sendspace = 2*1024; /* really max datagram size */
519 static u_long unpdg_recvspace = 4*1024;
520
521 static int unp_rights; /* file descriptors in flight */
522
523 SYSCTL_DECL(_net_local_stream);
524 SYSCTL_INT(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
525 &unpst_sendspace, 0, "");
526 SYSCTL_INT(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
527 &unpst_recvspace, 0, "");
528 SYSCTL_DECL(_net_local_dgram);
529 SYSCTL_INT(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
530 &unpdg_sendspace, 0, "");
531 SYSCTL_INT(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
532 &unpdg_recvspace, 0, "");
533 SYSCTL_DECL(_net_local);
534 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0, "");
535
536 static int
537 unp_attach(struct socket *so)
538 {
539 struct unpcb *unp;
540 int error = 0;
541
542 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
543 switch (so->so_type) {
544
545 case SOCK_STREAM:
546 error = soreserve(so, unpst_sendspace, unpst_recvspace);
547 break;
548
549 case SOCK_DGRAM:
550 error = soreserve(so, unpdg_sendspace, unpdg_recvspace);
551 break;
552
553 default:
554 panic("unp_attach");
555 }
556 if (error)
557 return (error);
558 }
559 unp = (struct unpcb*)zalloc(unp_zone);
560 if (unp == NULL)
561 return (ENOBUFS);
562 bzero(unp, sizeof *unp);
563 lck_mtx_lock(unp_mutex);
564 LIST_INIT(&unp->unp_refs);
565 unp->unp_socket = so;
566 unp->unp_gencnt = ++unp_gencnt;
567 unp_count++;
568 LIST_INSERT_HEAD(so->so_type == SOCK_DGRAM ? &unp_dhead
569 : &unp_shead, unp, unp_link);
570 so->so_pcb = (caddr_t)unp;
571 lck_mtx_unlock(unp_mutex);
572 return (0);
573 }
574
575 static void
576 unp_detach(struct unpcb *unp)
577 {
578 lck_mtx_assert(unp_mutex, LCK_MTX_ASSERT_OWNED);
579 LIST_REMOVE(unp, unp_link);
580 unp->unp_gencnt = ++unp_gencnt;
581 --unp_count;
582 if (unp->unp_vnode) {
583 struct vnode *tvp = unp->unp_vnode;
584 unp->unp_vnode->v_socket = 0;
585 unp->unp_vnode = 0;
586 vnode_rele(tvp); /* drop the usecount */
587 }
588 if (unp->unp_conn)
589 unp_disconnect(unp);
590 while (unp->unp_refs.lh_first)
591 unp_drop(unp->unp_refs.lh_first, ECONNRESET);
592 soisdisconnected(unp->unp_socket);
593 unp->unp_socket->so_flags |= SOF_PCBCLEARING; /* makes sure we're getting dealloced */
594 unp->unp_socket->so_pcb = 0;
595 if (unp_rights) {
596 /*
597 * Normally the receive buffer is flushed later,
598 * in sofree, but if our receive buffer holds references
599 * to descriptors that are now garbage, we will dispose
600 * of those descriptor references after the garbage collector
601 * gets them (resulting in a "panic: closef: count < 0").
602 */
603 sorflush(unp->unp_socket);
604 unp_gc();
605 }
606 if (unp->unp_addr)
607 FREE(unp->unp_addr, M_SONAME);
608 zfree(unp_zone, unp);
609 }
610
611 static int
612 unp_bind(
613 struct unpcb *unp,
614 struct sockaddr *nam,
615 struct proc *p)
616 {
617 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
618 struct vnode *vp, *dvp;
619 struct vnode_attr va;
620 struct vfs_context context;
621 int error, namelen;
622 struct nameidata nd;
623 char buf[SOCK_MAXADDRLEN];
624
625 context.vc_proc = p;
626 context.vc_ucred = p->p_ucred; /* XXX kauth_cred_get() ??? proxy */
627
628 if (unp->unp_vnode != NULL)
629 return (EINVAL);
630 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
631 if (namelen <= 0)
632 return EINVAL;
633 strncpy(buf, soun->sun_path, namelen);
634 buf[namelen] = 0; /* null-terminate the string */
635 NDINIT(&nd, CREATE, FOLLOW | LOCKPARENT, UIO_SYSSPACE32,
636 CAST_USER_ADDR_T(buf), &context);
637 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
638 error = namei(&nd);
639 if (error) {
640 return (error);
641 }
642 dvp = nd.ni_dvp;
643 vp = nd.ni_vp;
644
645 if (vp != NULL) {
646 /*
647 * need to do this before the vnode_put of dvp
648 * since we may have to release an fs_nodelock
649 */
650 nameidone(&nd);
651
652 vnode_put(dvp);
653 vnode_put(vp);
654
655 return (EADDRINUSE);
656 }
657
658 /* authorize before creating */
659 error = vnode_authorize(dvp, NULL, KAUTH_VNODE_ADD_FILE, &context);
660
661 if (!error) {
662 VATTR_INIT(&va);
663 VATTR_SET(&va, va_type, VSOCK);
664 VATTR_SET(&va, va_mode, (ACCESSPERMS & ~p->p_fd->fd_cmask));
665
666 /* create the socket */
667 error = vn_create(dvp, &vp, &nd.ni_cnd, &va, 0, &context);
668 }
669
670 nameidone(&nd);
671 vnode_put(dvp);
672
673 if (error) {
674 return (error);
675 }
676 vnode_ref(vp); /* gain a longterm reference */
677 vp->v_socket = unp->unp_socket;
678 unp->unp_vnode = vp;
679 unp->unp_addr = (struct sockaddr_un *)dup_sockaddr(nam, 1);
680 vnode_put(vp); /* drop the iocount */
681
682 return (0);
683 }
684
685 static int
686 unp_connect(
687 struct socket *so,
688 struct sockaddr *nam,
689 struct proc *p)
690 {
691 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
692 struct vnode *vp;
693 struct socket *so2, *so3;
694 struct unpcb *unp, *unp2, *unp3;
695 struct vfs_context context;
696 int error, len;
697 struct nameidata nd;
698 char buf[SOCK_MAXADDRLEN];
699
700 context.vc_proc = p;
701 context.vc_ucred = p->p_ucred; /* XXX kauth_cred_get() ??? proxy */
702 so2 = so3 = NULL;
703
704 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
705 if (len <= 0)
706 return EINVAL;
707 strncpy(buf, soun->sun_path, len);
708 buf[len] = 0;
709
710 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE32, CAST_USER_ADDR_T(buf), &context);
711 error = namei(&nd);
712 if (error) {
713 return (error);
714 }
715 nameidone(&nd);
716 vp = nd.ni_vp;
717 if (vp->v_type != VSOCK) {
718 error = ENOTSOCK;
719 goto bad;
720 }
721
722 error = vnode_authorize(vp, NULL, KAUTH_VNODE_WRITE_DATA, &context);
723 if (error)
724 goto bad;
725 so2 = vp->v_socket;
726 if (so2 == 0) {
727 error = ECONNREFUSED;
728 goto bad;
729 }
730
731 /* make sure the socket can't go away while we're connecting */
732 so2->so_usecount++;
733
734 if (so->so_type != so2->so_type) {
735 error = EPROTOTYPE;
736 goto bad;
737 }
738
739 /*
740 * Check if socket was connected while we were trying to
741 * acquire the funnel.
742 * XXX - probably shouldn't return an error for SOCK_DGRAM
743 */
744 if ((so->so_state & SS_ISCONNECTED) != 0) {
745 error = EISCONN;
746 goto bad;
747 }
748
749 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
750 if ((so2->so_options & SO_ACCEPTCONN) == 0 ||
751 (so3 = sonewconn(so2, 0, nam)) == 0) {
752 error = ECONNREFUSED;
753 goto bad;
754 }
755 unp = sotounpcb(so);
756 unp2 = sotounpcb(so2);
757 unp3 = sotounpcb(so3);
758 if (unp2->unp_addr)
759 unp3->unp_addr = (struct sockaddr_un *)
760 dup_sockaddr((struct sockaddr *)
761 unp2->unp_addr, 1);
762
763 /*
764 * unp_peercred management:
765 *
766 * The connecter's (client's) credentials are copied
767 * from its process structure at the time of connect()
768 * (which is now).
769 */
770 cru2x(p->p_ucred, &unp3->unp_peercred);
771 unp3->unp_flags |= UNP_HAVEPC;
772 /*
773 * The receiver's (server's) credentials are copied
774 * from the unp_peercred member of socket on which the
775 * former called listen(); unp_listen() cached that
776 * process's credentials at that time so we can use
777 * them now.
778 */
779 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
780 ("unp_connect: listener without cached peercred"));
781 memcpy(&unp->unp_peercred, &unp2->unp_peercred,
782 sizeof(unp->unp_peercred));
783 unp->unp_flags |= UNP_HAVEPC;
784
785 so2->so_usecount--; /* drop reference taken on so2 */
786 so2 = so3;
787 so3->so_usecount++; /* make sure we keep it around */
788 }
789 error = unp_connect2(so, so2);
790 bad:
791 if (so2 != NULL)
792 so2->so_usecount--; /* release count on socket */
793 vnode_put(vp);
794 return (error);
795 }
796
797 int
798 unp_connect2(
799 struct socket *so,
800 struct socket *so2)
801 {
802 struct unpcb *unp = sotounpcb(so);
803 struct unpcb *unp2;
804
805 if (so2->so_type != so->so_type)
806 return (EPROTOTYPE);
807 unp2 = sotounpcb(so2);
808
809 /* Verify both sockets are still opened */
810 if (unp == 0 || unp2 == 0)
811 return (EINVAL);
812
813 unp->unp_conn = unp2;
814 switch (so->so_type) {
815
816 case SOCK_DGRAM:
817 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
818 soisconnected(so);
819 break;
820
821 case SOCK_STREAM:
822 /* This takes care of socketpair */
823 if (!(unp->unp_flags & UNP_HAVEPC) && !(unp2->unp_flags & UNP_HAVEPC)) {
824 cru2x(kauth_cred_get(), &unp->unp_peercred);
825 unp->unp_flags |= UNP_HAVEPC;
826
827 cru2x(kauth_cred_get(), &unp2->unp_peercred);
828 unp2->unp_flags |= UNP_HAVEPC;
829 }
830 unp2->unp_conn = unp;
831 soisconnected(so);
832 soisconnected(so2);
833 break;
834
835 default:
836 panic("unp_connect2");
837 }
838 return (0);
839 }
840
841 static void
842 unp_disconnect(struct unpcb *unp)
843 {
844 struct unpcb *unp2 = unp->unp_conn;
845
846 if (unp2 == 0)
847 return;
848 lck_mtx_assert(unp_mutex, LCK_MTX_ASSERT_OWNED);
849 unp->unp_conn = 0;
850 switch (unp->unp_socket->so_type) {
851
852 case SOCK_DGRAM:
853 LIST_REMOVE(unp, unp_reflink);
854 unp->unp_socket->so_state &= ~SS_ISCONNECTED;
855 break;
856
857 case SOCK_STREAM:
858 soisdisconnected(unp->unp_socket);
859 unp2->unp_conn = 0;
860 soisdisconnected(unp2->unp_socket);
861 break;
862 }
863 }
864
865 #ifdef notdef
866 void
867 unp_abort(struct unpcb *unp)
868 {
869
870 unp_detach(unp);
871 }
872 #endif
873
874 static int
875 unp_pcblist SYSCTL_HANDLER_ARGS
876 {
877 int error, i, n;
878 struct unpcb *unp, **unp_list;
879 unp_gen_t gencnt;
880 struct xunpgen xug;
881 struct unp_head *head;
882
883 lck_mtx_lock(unp_mutex);
884 head = ((intptr_t)arg1 == SOCK_DGRAM ? &unp_dhead : &unp_shead);
885
886 /*
887 * The process of preparing the PCB list is too time-consuming and
888 * resource-intensive to repeat twice on every request.
889 */
890 if (req->oldptr == USER_ADDR_NULL) {
891 n = unp_count;
892 req->oldidx = 2 * (sizeof xug)
893 + (n + n/8) * sizeof(struct xunpcb);
894 lck_mtx_unlock(unp_mutex);
895 return 0;
896 }
897
898 if (req->newptr != USER_ADDR_NULL) {
899 lck_mtx_unlock(unp_mutex);
900 return EPERM;
901 }
902
903 /*
904 * OK, now we're committed to doing something.
905 */
906 gencnt = unp_gencnt;
907 n = unp_count;
908
909 bzero(&xug, sizeof(xug));
910 xug.xug_len = sizeof xug;
911 xug.xug_count = n;
912 xug.xug_gen = gencnt;
913 xug.xug_sogen = so_gencnt;
914 error = SYSCTL_OUT(req, &xug, sizeof xug);
915 if (error) {
916 lck_mtx_unlock(unp_mutex);
917 return error;
918 }
919
920 /*
921 * We are done if there is no pcb
922 */
923 if (n == 0) {
924 lck_mtx_unlock(unp_mutex);
925 return 0;
926 }
927
928 MALLOC(unp_list, struct unpcb **, n * sizeof *unp_list, M_TEMP, M_WAITOK);
929 if (unp_list == 0) {
930 lck_mtx_unlock(unp_mutex);
931 return ENOMEM;
932 }
933
934 for (unp = head->lh_first, i = 0; unp && i < n;
935 unp = unp->unp_link.le_next) {
936 if (unp->unp_gencnt <= gencnt)
937 unp_list[i++] = unp;
938 }
939 n = i; /* in case we lost some during malloc */
940
941 error = 0;
942 for (i = 0; i < n; i++) {
943 unp = unp_list[i];
944 if (unp->unp_gencnt <= gencnt) {
945 struct xunpcb xu;
946
947 bzero(&xu, sizeof(xu));
948 xu.xu_len = sizeof xu;
949 xu.xu_unpp = (struct unpcb_compat *)unp;
950 /*
951 * XXX - need more locking here to protect against
952 * connect/disconnect races for SMP.
953 */
954 if (unp->unp_addr)
955 bcopy(unp->unp_addr, &xu.xu_addr,
956 unp->unp_addr->sun_len);
957 if (unp->unp_conn && unp->unp_conn->unp_addr)
958 bcopy(unp->unp_conn->unp_addr,
959 &xu.xu_caddr,
960 unp->unp_conn->unp_addr->sun_len);
961 bcopy(unp, &xu.xu_unp, sizeof(xu.xu_unp));
962 sotoxsocket(unp->unp_socket, &xu.xu_socket);
963 error = SYSCTL_OUT(req, &xu, sizeof xu);
964 }
965 }
966 if (!error) {
967 /*
968 * Give the user an updated idea of our state.
969 * If the generation differs from what we told
970 * her before, she knows that something happened
971 * while we were processing this request, and it
972 * might be necessary to retry.
973 */
974 bzero(&xug, sizeof(xug));
975 xug.xug_len = sizeof xug;
976 xug.xug_gen = unp_gencnt;
977 xug.xug_sogen = so_gencnt;
978 xug.xug_count = unp_count;
979 error = SYSCTL_OUT(req, &xug, sizeof xug);
980 }
981 FREE(unp_list, M_TEMP);
982 lck_mtx_unlock(unp_mutex);
983 return error;
984 }
985
986 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD,
987 (caddr_t)(long)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
988 "List of active local datagram sockets");
989 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD,
990 (caddr_t)(long)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
991 "List of active local stream sockets");
992
993 static void
994 unp_shutdown(struct unpcb *unp)
995 {
996 struct socket *so;
997
998 if (unp->unp_socket->so_type == SOCK_STREAM && unp->unp_conn &&
999 (so = unp->unp_conn->unp_socket))
1000 socantrcvmore(so);
1001 }
1002
1003 static void
1004 unp_drop(
1005 struct unpcb *unp,
1006 int errno)
1007 {
1008 struct socket *so = unp->unp_socket;
1009
1010 so->so_error = errno;
1011 unp_disconnect(unp);
1012 }
1013
1014 #ifdef notdef
1015 void
1016 unp_drain()
1017 {
1018
1019 }
1020 #endif
1021
1022 int
1023 unp_externalize(struct mbuf *rights)
1024 {
1025 struct proc *p = current_proc(); /* XXX */
1026 int i;
1027 struct cmsghdr *cm = mtod(rights, struct cmsghdr *);
1028 struct fileglob **rp = (struct fileglob **)(cm + 1);
1029 struct fileproc *fp;
1030 struct fileglob *fg;
1031 int newfds = (cm->cmsg_len - sizeof(*cm)) / sizeof (int);
1032 int f;
1033
1034 proc_fdlock(p);
1035
1036 /*
1037 * if the new FD's will not fit, then we free them all
1038 */
1039 if (!fdavail(p, newfds)) {
1040 for (i = 0; i < newfds; i++) {
1041 fg = *rp;
1042 unp_discard_fdlocked(fg, p);
1043 *rp++ = 0;
1044 }
1045 proc_fdunlock(p);
1046
1047 return (EMSGSIZE);
1048 }
1049 /*
1050 * now change each pointer to an fd in the global table to
1051 * an integer that is the index to the local fd table entry
1052 * that we set up to point to the global one we are transferring.
1053 * XXX this assumes a pointer and int are the same size...!
1054 */
1055 for (i = 0; i < newfds; i++) {
1056 if (fdalloc(p, 0, &f))
1057 panic("unp_externalize");
1058 fg = *rp;
1059 MALLOC_ZONE(fp, struct fileproc *, sizeof(struct fileproc), M_FILEPROC, M_WAITOK);
1060 bzero(fp, sizeof(struct fileproc));
1061 fp->f_iocount = 0;
1062 fp->f_fglob = fg;
1063 p->p_fd->fd_ofiles[f] = fp;
1064 fg_removeuipc(fg);
1065 *fdflags(p, f) &= ~UF_RESERVED;
1066 unp_rights--;
1067 *(int *)rp++ = f;
1068 }
1069 proc_fdunlock(p);
1070
1071 return (0);
1072 }
1073
1074 void
1075 unp_init(void)
1076 {
1077 unp_zone = zinit(sizeof(struct unpcb),
1078 (nmbclusters * sizeof(struct unpcb)),
1079 4096, "unpzone");
1080 if (unp_zone == 0)
1081 panic("unp_init");
1082 LIST_INIT(&unp_dhead);
1083 LIST_INIT(&unp_shead);
1084
1085 unp_mutex = localdomain.dom_mtx;
1086 }
1087
1088 #ifndef MIN
1089 #define MIN(a,b) (((a)<(b))?(a):(b))
1090 #endif
1091
1092 static int
1093 unp_internalize(
1094 struct mbuf *control,
1095 struct proc *p)
1096 {
1097 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1098 struct fileglob **rp;
1099 struct fileproc *fp;
1100 register int i, error;
1101 int oldfds;
1102 int fdgetf_noref(proc_t, struct fileglob **, struct fileproc **);
1103
1104 if (cm->cmsg_type != SCM_RIGHTS || cm->cmsg_level != SOL_SOCKET ||
1105 cm->cmsg_len != control->m_len) {
1106 return (EINVAL);
1107 }
1108 oldfds = (cm->cmsg_len - sizeof (*cm)) / sizeof (int);
1109
1110 proc_fdlock(p);
1111 rp = (struct fileglob **)(cm + 1);
1112
1113 for (i = 0; i < oldfds; i++) {
1114 if (error = fdgetf_noref(p, *(int *)rp++, (struct fileglob **)0)) {
1115 proc_fdunlock(p);
1116 return (error);
1117 }
1118 }
1119 rp = (struct fileglob **)(cm + 1);
1120
1121 for (i = 0; i < oldfds; i++) {
1122 (void) fdgetf_noref(p, *(int *)rp, &fp);
1123 fg_insertuipc(fp->f_fglob);
1124 *rp++ = fp->f_fglob;
1125 unp_rights++;
1126 }
1127 proc_fdunlock(p);
1128
1129 return (0);
1130 }
1131
1132 static int unp_defer, unp_gcing;
1133
1134 static void
1135 unp_gc()
1136 {
1137 register struct fileglob *fg, *nextfg;
1138 register struct socket *so;
1139 struct fileglob **extra_ref, **fpp;
1140 int nunref, i;
1141
1142 lck_mtx_lock(uipc_lock);
1143 if (unp_gcing) {
1144 lck_mtx_unlock(uipc_lock);
1145 return;
1146 }
1147 unp_gcing = 1;
1148 unp_defer = 0;
1149 lck_mtx_unlock(uipc_lock);
1150 /*
1151 * before going through all this, set all FDs to
1152 * be NOT defered and NOT externally accessible
1153 */
1154 for (fg = fmsghead.lh_first; fg != 0; fg = fg->f_msglist.le_next) {
1155 lck_mtx_lock(&fg->fg_lock);
1156 fg->fg_flag &= ~(FMARK|FDEFER);
1157 lck_mtx_unlock(&fg->fg_lock);
1158 }
1159 do {
1160 for (fg = fmsghead.lh_first; fg != 0; fg = fg->f_msglist.le_next) {
1161 lck_mtx_lock(&fg->fg_lock);
1162 /*
1163 * If the file is not open, skip it
1164 */
1165 if (fg->fg_count == 0) {
1166 lck_mtx_unlock(&fg->fg_lock);
1167 continue;
1168 }
1169 /*
1170 * If we already marked it as 'defer' in a
1171 * previous pass, then try process it this time
1172 * and un-mark it
1173 */
1174 if (fg->fg_flag & FDEFER) {
1175 fg->fg_flag &= ~FDEFER;
1176 unp_defer--;
1177 } else {
1178 /*
1179 * if it's not defered, then check if it's
1180 * already marked.. if so skip it
1181 */
1182 if (fg->fg_flag & FMARK){
1183 lck_mtx_unlock(&fg->fg_lock);
1184 continue;
1185 }
1186 /*
1187 * If all references are from messages
1188 * in transit, then skip it. it's not
1189 * externally accessible.
1190 */
1191 if (fg->fg_count == fg->fg_msgcount) {
1192 lck_mtx_unlock(&fg->fg_lock);
1193 continue;
1194 }
1195 /*
1196 * If it got this far then it must be
1197 * externally accessible.
1198 */
1199 fg->fg_flag |= FMARK;
1200 }
1201 /*
1202 * either it was defered, or it is externally
1203 * accessible and not already marked so.
1204 * Now check if it is possibly one of OUR sockets.
1205 */
1206 if (fg->fg_type != DTYPE_SOCKET ||
1207 (so = (struct socket *)fg->fg_data) == 0) {
1208 lck_mtx_unlock(&fg->fg_lock);
1209 continue;
1210 }
1211 if (so->so_proto->pr_domain != &localdomain ||
1212 (so->so_proto->pr_flags&PR_RIGHTS) == 0) {
1213 lck_mtx_unlock(&fg->fg_lock);
1214 continue;
1215 }
1216 #ifdef notdef
1217 /* if this code is enabled need to run under network funnel */
1218 if (so->so_rcv.sb_flags & SB_LOCK) {
1219 /*
1220 * This is problematical; it's not clear
1221 * we need to wait for the sockbuf to be
1222 * unlocked (on a uniprocessor, at least),
1223 * and it's also not clear what to do
1224 * if sbwait returns an error due to receipt
1225 * of a signal. If sbwait does return
1226 * an error, we'll go into an infinite
1227 * loop. Delete all of this for now.
1228 */
1229 (void) sbwait(&so->so_rcv);
1230 goto restart;
1231 }
1232 #endif
1233 /*
1234 * So, Ok, it's one of our sockets and it IS externally
1235 * accessible (or was defered). Now we look
1236 * to see if we hold any file descriptors in its
1237 * message buffers. Follow those links and mark them
1238 * as accessible too.
1239 */
1240 unp_scan(so->so_rcv.sb_mb, unp_mark);
1241 lck_mtx_unlock(&fg->fg_lock);
1242 }
1243 } while (unp_defer);
1244 /*
1245 * We grab an extra reference to each of the file table entries
1246 * that are not otherwise accessible and then free the rights
1247 * that are stored in messages on them.
1248 *
1249 * The bug in the orginal code is a little tricky, so I'll describe
1250 * what's wrong with it here.
1251 *
1252 * It is incorrect to simply unp_discard each entry for f_msgcount
1253 * times -- consider the case of sockets A and B that contain
1254 * references to each other. On a last close of some other socket,
1255 * we trigger a gc since the number of outstanding rights (unp_rights)
1256 * is non-zero. If during the sweep phase the gc code un_discards,
1257 * we end up doing a (full) closef on the descriptor. A closef on A
1258 * results in the following chain. Closef calls soo_close, which
1259 * calls soclose. Soclose calls first (through the switch
1260 * uipc_usrreq) unp_detach, which re-invokes unp_gc. Unp_gc simply
1261 * returns because the previous instance had set unp_gcing, and
1262 * we return all the way back to soclose, which marks the socket
1263 * with SS_NOFDREF, and then calls sofree. Sofree calls sorflush
1264 * to free up the rights that are queued in messages on the socket A,
1265 * i.e., the reference on B. The sorflush calls via the dom_dispose
1266 * switch unp_dispose, which unp_scans with unp_discard. This second
1267 * instance of unp_discard just calls closef on B.
1268 *
1269 * Well, a similar chain occurs on B, resulting in a sorflush on B,
1270 * which results in another closef on A. Unfortunately, A is already
1271 * being closed, and the descriptor has already been marked with
1272 * SS_NOFDREF, and soclose panics at this point.
1273 *
1274 * Here, we first take an extra reference to each inaccessible
1275 * descriptor. Then, we call sorflush ourself, since we know
1276 * it is a Unix domain socket anyhow. After we destroy all the
1277 * rights carried in messages, we do a last closef to get rid
1278 * of our extra reference. This is the last close, and the
1279 * unp_detach etc will shut down the socket.
1280 *
1281 * 91/09/19, bsy@cs.cmu.edu
1282 */
1283 extra_ref = _MALLOC(nfiles * sizeof(struct fileglob *), M_FILEGLOB, M_WAITOK);
1284 for (nunref = 0, fg = fmsghead.lh_first, fpp = extra_ref; fg != 0;
1285 fg = nextfg) {
1286 lck_mtx_lock(&fg->fg_lock);
1287
1288 nextfg = fg->f_msglist.le_next;
1289 /*
1290 * If it's not open, skip it
1291 */
1292 if (fg->fg_count == 0) {
1293 lck_mtx_unlock(&fg->fg_lock);
1294 continue;
1295 }
1296 /*
1297 * If all refs are from msgs, and it's not marked accessible
1298 * then it must be referenced from some unreachable cycle
1299 * of (shut-down) FDs, so include it in our
1300 * list of FDs to remove
1301 */
1302 if (fg->fg_count == fg->fg_msgcount && !(fg->fg_flag & FMARK)) {
1303 fg->fg_count++;
1304 *fpp++ = fg;
1305 nunref++;
1306 }
1307 lck_mtx_unlock(&fg->fg_lock);
1308 }
1309 /*
1310 * for each FD on our hit list, do the following two things
1311 */
1312 for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
1313 struct fileglob *tfg;
1314
1315 tfg = *fpp;
1316
1317 if (tfg->fg_type == DTYPE_SOCKET && tfg->fg_data != NULL) {
1318 sorflush((struct socket *)(tfg->fg_data));
1319 }
1320 }
1321 for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp)
1322 closef_locked((struct fileproc *)0, *fpp, (struct proc *) NULL);
1323 unp_gcing = 0;
1324 FREE((caddr_t)extra_ref, M_FILEGLOB);
1325
1326 }
1327
1328 void
1329 unp_dispose(struct mbuf *m)
1330 {
1331
1332 if (m) {
1333 unp_scan(m, unp_discard);
1334 }
1335 }
1336
1337 static int
1338 unp_listen(
1339 struct unpcb *unp,
1340 struct proc *p)
1341 {
1342
1343 cru2x(p->p_ucred, &unp->unp_peercred);
1344 unp->unp_flags |= UNP_HAVEPCCACHED;
1345 return (0);
1346 }
1347
1348 /* should run under kernel funnel */
1349 static void
1350 unp_scan(
1351 struct mbuf *m0,
1352 void (*op)(struct fileglob *))
1353 {
1354 struct mbuf *m;
1355 struct fileglob **rp;
1356 struct cmsghdr *cm;
1357 int i;
1358 int qfds;
1359
1360 while (m0) {
1361 for (m = m0; m; m = m->m_next)
1362 if (m->m_type == MT_CONTROL &&
1363 (size_t) m->m_len >= sizeof(*cm)) {
1364 cm = mtod(m, struct cmsghdr *);
1365 if (cm->cmsg_level != SOL_SOCKET ||
1366 cm->cmsg_type != SCM_RIGHTS)
1367 continue;
1368 qfds = (cm->cmsg_len - sizeof *cm)
1369 / sizeof (struct fileglob *);
1370 rp = (struct fileglob **)(cm + 1);
1371 for (i = 0; i < qfds; i++)
1372 (*op)(*rp++);
1373 break; /* XXX, but saves time */
1374 }
1375 m0 = m0->m_act;
1376 }
1377 }
1378
1379 /* should run under kernel funnel */
1380 static void
1381 unp_mark(struct fileglob *fg)
1382 {
1383 lck_mtx_lock(&fg->fg_lock);
1384
1385 if (fg->fg_flag & FMARK) {
1386 lck_mtx_unlock(&fg->fg_lock);
1387 return;
1388 }
1389 fg->fg_flag |= (FMARK|FDEFER);
1390
1391 lck_mtx_unlock(&fg->fg_lock);
1392
1393 unp_defer++;
1394 }
1395
1396 /* should run under kernel funnel */
1397 static void
1398 unp_discard(fg)
1399 struct fileglob *fg;
1400 {
1401 struct proc *p = current_proc(); /* XXX */
1402
1403 proc_fdlock(p);
1404 unp_discard_fdlocked(fg, p);
1405 proc_fdunlock(p);
1406 }
1407 static void
1408 unp_discard_fdlocked(fg, p)
1409 struct fileglob *fg;
1410 struct proc *p;
1411 {
1412
1413 fg_removeuipc(fg);
1414
1415 unp_rights--;
1416 (void) closef_locked((struct fileproc *)0, fg, p);
1417 }