Merge branch 'vendor/FILE'
[dragonfly.git] / sys / kern / uipc_usrreq.c
1 /*
2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *      From: @(#)uipc_usrreq.c 8.3 (Berkeley) 1/4/94
34  * $FreeBSD: src/sys/kern/uipc_usrreq.c,v 1.54.2.10 2003/03/04 17:28:09 nectar Exp $
35  * $DragonFly: src/sys/kern/uipc_usrreq.c,v 1.44 2008/09/06 05:44:58 dillon Exp $
36  */
37
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/kernel.h>
41 #include <sys/domain.h>
42 #include <sys/fcntl.h>
43 #include <sys/malloc.h>         /* XXX must be before <sys/file.h> */
44 #include <sys/proc.h>
45 #include <sys/file.h>
46 #include <sys/filedesc.h>
47 #include <sys/mbuf.h>
48 #include <sys/nlookup.h>
49 #include <sys/protosw.h>
50 #include <sys/socket.h>
51 #include <sys/socketvar.h>
52 #include <sys/resourcevar.h>
53 #include <sys/stat.h>
54 #include <sys/mount.h>
55 #include <sys/sysctl.h>
56 #include <sys/un.h>
57 #include <sys/unpcb.h>
58 #include <sys/vnode.h>
59 #include <sys/file2.h>
60 #include <sys/spinlock2.h>
61
62
63 static  MALLOC_DEFINE(M_UNPCB, "unpcb", "unpcb struct");
64 static  unp_gen_t unp_gencnt;
65 static  u_int unp_count;
66
67 static  struct unp_head unp_shead, unp_dhead;
68
69 /*
70  * Unix communications domain.
71  *
72  * TODO:
73  *      RDM
74  *      rethink name space problems
75  *      need a proper out-of-band
76  *      lock pushdown
77  */
78 static struct   sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
79 static ino_t    unp_ino;                /* prototype for fake inode numbers */
80
81 static int     unp_attach (struct socket *, struct pru_attach_info *);
82 static void    unp_detach (struct unpcb *);
83 static int     unp_bind (struct unpcb *,struct sockaddr *, struct thread *);
84 static int     unp_connect (struct socket *,struct sockaddr *,
85                                 struct thread *);
86 static void    unp_disconnect (struct unpcb *);
87 static void    unp_shutdown (struct unpcb *);
88 static void    unp_drop (struct unpcb *, int);
89 static void    unp_gc (void);
90 static int     unp_gc_clearmarks(struct file *, void *);
91 static int     unp_gc_checkmarks(struct file *, void *);
92 static int     unp_gc_checkrefs(struct file *, void *);
93 static int     unp_revoke_gc_check(struct file *, void *);
94 static void    unp_scan (struct mbuf *, void (*)(struct file *, void *),
95                                 void *data);
96 static void    unp_mark (struct file *, void *data);
97 static void    unp_discard (struct file *, void *);
98 static int     unp_internalize (struct mbuf *, struct thread *);
99 static int     unp_listen (struct unpcb *, struct thread *);
100 static void    unp_fp_externalize(struct proc *p, struct file *fp, int fd);
101
102 static int
103 uipc_abort(struct socket *so)
104 {
105         struct unpcb *unp = so->so_pcb;
106
107         if (unp == NULL)
108                 return EINVAL;
109         unp_drop(unp, ECONNABORTED);
110         unp_detach(unp);
111         sofree(so);
112         return 0;
113 }
114
115 static int
116 uipc_accept(struct socket *so, struct sockaddr **nam)
117 {
118         struct unpcb *unp = so->so_pcb;
119
120         if (unp == NULL)
121                 return EINVAL;
122
123         /*
124          * Pass back name of connected socket,
125          * if it was bound and we are still connected
126          * (our peer may have closed already!).
127          */
128         if (unp->unp_conn && unp->unp_conn->unp_addr) {
129                 *nam = dup_sockaddr((struct sockaddr *)unp->unp_conn->unp_addr);
130         } else {
131                 *nam = dup_sockaddr((struct sockaddr *)&sun_noname);
132         }
133         return 0;
134 }
135
136 static int
137 uipc_attach(struct socket *so, int proto, struct pru_attach_info *ai)
138 {
139         struct unpcb *unp = so->so_pcb;
140
141         if (unp != NULL)
142                 return EISCONN;
143         return unp_attach(so, ai);
144 }
145
146 static int
147 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
148 {
149         struct unpcb *unp = so->so_pcb;
150
151         if (unp == NULL)
152                 return EINVAL;
153         return unp_bind(unp, nam, td);
154 }
155
156 static int
157 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
158 {
159         struct unpcb *unp = so->so_pcb;
160
161         if (unp == NULL)
162                 return EINVAL;
163         return unp_connect(so, nam, td);
164 }
165
166 static int
167 uipc_connect2(struct socket *so1, struct socket *so2)
168 {
169         struct unpcb *unp = so1->so_pcb;
170
171         if (unp == NULL)
172                 return EINVAL;
173
174         return unp_connect2(so1, so2);
175 }
176
177 /* control is EOPNOTSUPP */
178
179 static int
180 uipc_detach(struct socket *so)
181 {
182         struct unpcb *unp = so->so_pcb;
183
184         if (unp == NULL)
185                 return EINVAL;
186
187         unp_detach(unp);
188         return 0;
189 }
190
191 static int
192 uipc_disconnect(struct socket *so)
193 {
194         struct unpcb *unp = so->so_pcb;
195
196         if (unp == NULL)
197                 return EINVAL;
198         unp_disconnect(unp);
199         return 0;
200 }
201
202 static int
203 uipc_listen(struct socket *so, struct thread *td)
204 {
205         struct unpcb *unp = so->so_pcb;
206
207         if (unp == NULL || unp->unp_vnode == NULL)
208                 return EINVAL;
209         return unp_listen(unp, td);
210 }
211
212 static int
213 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
214 {
215         struct unpcb *unp = so->so_pcb;
216
217         if (unp == NULL)
218                 return EINVAL;
219         if (unp->unp_conn && unp->unp_conn->unp_addr)
220                 *nam = dup_sockaddr((struct sockaddr *)unp->unp_conn->unp_addr);
221         else {
222                 /*
223                  * XXX: It seems that this test always fails even when
224                  * connection is established.  So, this else clause is
225                  * added as workaround to return PF_LOCAL sockaddr.
226                  */
227                 *nam = dup_sockaddr((struct sockaddr *)&sun_noname);
228         }
229         return 0;
230 }
231
232 static int
233 uipc_rcvd(struct socket *so, int flags)
234 {
235         struct unpcb *unp = so->so_pcb;
236         struct socket *so2;
237
238         if (unp == NULL)
239                 return EINVAL;
240         switch (so->so_type) {
241         case SOCK_DGRAM:
242                 panic("uipc_rcvd DGRAM?");
243                 /*NOTREACHED*/
244
245         case SOCK_STREAM:
246         case SOCK_SEQPACKET:
247                 if (unp->unp_conn == NULL)
248                         break;
249                 /*
250                  * Because we are transfering mbufs directly to the
251                  * peer socket we have to use SSB_STOP on the sender
252                  * to prevent it from building up infinite mbufs.
253                  */
254                 so2 = unp->unp_conn->unp_socket;
255                 if (so->so_rcv.ssb_cc < so2->so_snd.ssb_hiwat &&
256                     so->so_rcv.ssb_mbcnt < so2->so_snd.ssb_mbmax
257                 ) {
258                         so2->so_snd.ssb_flags &= ~SSB_STOP;
259                         sowwakeup(so2);
260                 }
261                 break;
262
263         default:
264                 panic("uipc_rcvd unknown socktype");
265         }
266         return 0;
267 }
268
269 /* pru_rcvoob is EOPNOTSUPP */
270
271 static int
272 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
273           struct mbuf *control, struct thread *td)
274 {
275         int error = 0;
276         struct unpcb *unp = so->so_pcb;
277         struct socket *so2;
278
279         if (unp == NULL) {
280                 error = EINVAL;
281                 goto release;
282         }
283         if (flags & PRUS_OOB) {
284                 error = EOPNOTSUPP;
285                 goto release;
286         }
287
288         if (control && (error = unp_internalize(control, td)))
289                 goto release;
290
291         switch (so->so_type) {
292         case SOCK_DGRAM: 
293         {
294                 struct sockaddr *from;
295
296                 if (nam) {
297                         if (unp->unp_conn) {
298                                 error = EISCONN;
299                                 break;
300                         }
301                         error = unp_connect(so, nam, td);
302                         if (error)
303                                 break;
304                 } else {
305                         if (unp->unp_conn == NULL) {
306                                 error = ENOTCONN;
307                                 break;
308                         }
309                 }
310                 so2 = unp->unp_conn->unp_socket;
311                 if (unp->unp_addr)
312                         from = (struct sockaddr *)unp->unp_addr;
313                 else
314                         from = &sun_noname;
315                 if (ssb_appendaddr(&so2->so_rcv, from, m, control)) {
316                         sorwakeup(so2);
317                         m = NULL;
318                         control = NULL;
319                 } else {
320                         error = ENOBUFS;
321                 }
322                 if (nam)
323                         unp_disconnect(unp);
324                 break;
325         }
326
327         case SOCK_STREAM:
328         case SOCK_SEQPACKET:
329                 /* Connect if not connected yet. */
330                 /*
331                  * Note: A better implementation would complain
332                  * if not equal to the peer's address.
333                  */
334                 if (!(so->so_state & SS_ISCONNECTED)) {
335                         if (nam) {
336                                 error = unp_connect(so, nam, td);
337                                 if (error)
338                                         break;  /* XXX */
339                         } else {
340                                 error = ENOTCONN;
341                                 break;
342                         }
343                 }
344
345                 if (so->so_state & SS_CANTSENDMORE) {
346                         error = EPIPE;
347                         break;
348                 }
349                 if (unp->unp_conn == NULL)
350                         panic("uipc_send connected but no connection?");
351                 so2 = unp->unp_conn->unp_socket;
352                 /*
353                  * Send to paired receive port, and then reduce
354                  * send buffer hiwater marks to maintain backpressure.
355                  * Wake up readers.
356                  */
357                 if (control) {
358                         if (ssb_appendcontrol(&so2->so_rcv, m, control)) {
359                                 control = NULL;
360                                 m = NULL;
361                         }
362                 } else if (so->so_type == SOCK_SEQPACKET) {
363                         sbappendrecord(&so2->so_rcv.sb, m);
364                         m = NULL;
365                 } else {
366                         sbappend(&so2->so_rcv.sb, m);
367                         m = NULL;
368                 }
369
370                 /*
371                  * Because we are transfering mbufs directly to the
372                  * peer socket we have to use SSB_STOP on the sender
373                  * to prevent it from building up infinite mbufs.
374                  */
375                 if (so2->so_rcv.ssb_cc >= so->so_snd.ssb_hiwat ||
376                     so2->so_rcv.ssb_mbcnt >= so->so_snd.ssb_mbmax
377                 ) {
378                         so->so_snd.ssb_flags |= SSB_STOP;
379                 }
380                 sorwakeup(so2);
381                 break;
382
383         default:
384                 panic("uipc_send unknown socktype");
385         }
386
387         /*
388          * SEND_EOF is equivalent to a SEND followed by a SHUTDOWN.
389          */
390         if (flags & PRUS_EOF) {
391                 socantsendmore(so);
392                 unp_shutdown(unp);
393         }
394
395         if (control && error != 0)
396                 unp_dispose(control);
397
398 release:
399         if (control)
400                 m_freem(control);
401         if (m)
402                 m_freem(m);
403         return error;
404 }
405
406 static int
407 uipc_sense(struct socket *so, struct stat *sb)
408 {
409         struct unpcb *unp = so->so_pcb;
410
411         if (unp == NULL)
412                 return EINVAL;
413         sb->st_blksize = so->so_snd.ssb_hiwat;
414         sb->st_dev = NOUDEV;
415         if (unp->unp_ino == 0)          /* make up a non-zero inode number */
416                 unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
417         sb->st_ino = unp->unp_ino;
418         return (0);
419 }
420
421 static int
422 uipc_shutdown(struct socket *so)
423 {
424         struct unpcb *unp = so->so_pcb;
425
426         if (unp == NULL)
427                 return EINVAL;
428         socantsendmore(so);
429         unp_shutdown(unp);
430         return 0;
431 }
432
433 static int
434 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
435 {
436         struct unpcb *unp = so->so_pcb;
437
438         if (unp == NULL)
439                 return EINVAL;
440         if (unp->unp_addr)
441                 *nam = dup_sockaddr((struct sockaddr *)unp->unp_addr);
442         return 0;
443 }
444
445 struct pr_usrreqs uipc_usrreqs = {
446         .pru_abort = uipc_abort,
447         .pru_accept = uipc_accept,
448         .pru_attach = uipc_attach,
449         .pru_bind = uipc_bind,
450         .pru_connect = uipc_connect,
451         .pru_connect2 = uipc_connect2,
452         .pru_control = pru_control_notsupp,
453         .pru_detach = uipc_detach,
454         .pru_disconnect = uipc_disconnect,
455         .pru_listen = uipc_listen,
456         .pru_peeraddr = uipc_peeraddr,
457         .pru_rcvd = uipc_rcvd,
458         .pru_rcvoob = pru_rcvoob_notsupp,
459         .pru_send = uipc_send,
460         .pru_sense = uipc_sense,
461         .pru_shutdown = uipc_shutdown,
462         .pru_sockaddr = uipc_sockaddr,
463         .pru_sosend = sosend,
464         .pru_soreceive = soreceive,
465         .pru_sopoll = sopoll
466 };
467
468 int
469 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
470 {
471         struct unpcb *unp = so->so_pcb;
472         int error = 0;
473
474         switch (sopt->sopt_dir) {
475         case SOPT_GET:
476                 switch (sopt->sopt_name) {
477                 case LOCAL_PEERCRED:
478                         if (unp->unp_flags & UNP_HAVEPC)
479                                 soopt_from_kbuf(sopt, &unp->unp_peercred,
480                                                 sizeof(unp->unp_peercred));
481                         else {
482                                 if (so->so_type == SOCK_STREAM)
483                                         error = ENOTCONN;
484                                 else if (so->so_type == SOCK_SEQPACKET)
485                                         error = ENOTCONN;
486                                 else
487                                         error = EINVAL;
488                         }
489                         break;
490                 default:
491                         error = EOPNOTSUPP;
492                         break;
493                 }
494                 break;
495         case SOPT_SET:
496         default:
497                 error = EOPNOTSUPP;
498                 break;
499         }
500         return (error);
501 }
502         
503 /*
504  * Both send and receive buffers are allocated PIPSIZ bytes of buffering
505  * for stream sockets, although the total for sender and receiver is
506  * actually only PIPSIZ.
507  *
508  * Datagram sockets really use the sendspace as the maximum datagram size,
509  * and don't really want to reserve the sendspace.  Their recvspace should
510  * be large enough for at least one max-size datagram plus address.
511  *
512  * We want the local send/recv space to be significant larger then lo0's
513  * mtu of 16384.
514  */
515 #ifndef PIPSIZ
516 #define PIPSIZ  57344
517 #endif
518 static u_long   unpst_sendspace = PIPSIZ;
519 static u_long   unpst_recvspace = PIPSIZ;
520 static u_long   unpdg_sendspace = 2*1024;       /* really max datagram size */
521 static u_long   unpdg_recvspace = 4*1024;
522
523 static int      unp_rights;                     /* file descriptors in flight */
524 static struct spinlock unp_spin = SPINLOCK_INITIALIZER(&unp_spin);
525
526 SYSCTL_DECL(_net_local_seqpacket);
527 SYSCTL_DECL(_net_local_stream);
528 SYSCTL_INT(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW, 
529            &unpst_sendspace, 0, "");
530 SYSCTL_INT(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
531            &unpst_recvspace, 0, "");
532
533 SYSCTL_DECL(_net_local_dgram);
534 SYSCTL_INT(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
535            &unpdg_sendspace, 0, "");
536 SYSCTL_INT(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
537            &unpdg_recvspace, 0, "");
538
539 SYSCTL_DECL(_net_local);
540 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0, "");
541
542 static int
543 unp_attach(struct socket *so, struct pru_attach_info *ai)
544 {
545         struct unpcb *unp;
546         int error;
547
548         if (so->so_snd.ssb_hiwat == 0 || so->so_rcv.ssb_hiwat == 0) {
549                 switch (so->so_type) {
550
551                 case SOCK_STREAM:
552                 case SOCK_SEQPACKET:
553                         error = soreserve(so, unpst_sendspace, unpst_recvspace,
554                                           ai->sb_rlimit);
555                         break;
556
557                 case SOCK_DGRAM:
558                         error = soreserve(so, unpdg_sendspace, unpdg_recvspace,
559                                           ai->sb_rlimit);
560                         break;
561
562                 default:
563                         panic("unp_attach");
564                 }
565                 if (error)
566                         return (error);
567         }
568         unp = kmalloc(sizeof(*unp), M_UNPCB, M_NOWAIT|M_ZERO);
569         if (unp == NULL)
570                 return (ENOBUFS);
571         unp->unp_gencnt = ++unp_gencnt;
572         unp_count++;
573         LIST_INIT(&unp->unp_refs);
574         unp->unp_socket = so;
575         unp->unp_rvnode = ai->fd_rdir;          /* jail cruft XXX JH */
576         LIST_INSERT_HEAD(so->so_type == SOCK_DGRAM ? &unp_dhead
577                          : &unp_shead, unp, unp_link);
578         so->so_pcb = (caddr_t)unp;
579         return (0);
580 }
581
582 static void
583 unp_detach(struct unpcb *unp)
584 {
585         LIST_REMOVE(unp, unp_link);
586         unp->unp_gencnt = ++unp_gencnt;
587         --unp_count;
588         if (unp->unp_vnode) {
589                 unp->unp_vnode->v_socket = NULL;
590                 vrele(unp->unp_vnode);
591                 unp->unp_vnode = NULL;
592         }
593         if (unp->unp_conn)
594                 unp_disconnect(unp);
595         while (!LIST_EMPTY(&unp->unp_refs))
596                 unp_drop(LIST_FIRST(&unp->unp_refs), ECONNRESET);
597         soisdisconnected(unp->unp_socket);
598         unp->unp_socket->so_pcb = NULL;
599         if (unp_rights) {
600                 /*
601                  * Normally the receive buffer is flushed later,
602                  * in sofree, but if our receive buffer holds references
603                  * to descriptors that are now garbage, we will dispose
604                  * of those descriptor references after the garbage collector
605                  * gets them (resulting in a "panic: closef: count < 0").
606                  */
607                 sorflush(unp->unp_socket);
608                 unp_gc();
609         }
610         if (unp->unp_addr)
611                 kfree(unp->unp_addr, M_SONAME);
612         kfree(unp, M_UNPCB);
613 }
614
615 static int
616 unp_bind(struct unpcb *unp, struct sockaddr *nam, struct thread *td)
617 {
618         struct proc *p = td->td_proc;
619         struct sockaddr_un *soun = (struct sockaddr_un *)nam;
620         struct vnode *vp;
621         struct vattr vattr;
622         int error, namelen;
623         struct nlookupdata nd;
624         char buf[SOCK_MAXADDRLEN];
625
626         if (unp->unp_vnode != NULL)
627                 return (EINVAL);
628         namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
629         if (namelen <= 0)
630                 return (EINVAL);
631         strncpy(buf, soun->sun_path, namelen);
632         buf[namelen] = 0;       /* null-terminate the string */
633         error = nlookup_init(&nd, buf, UIO_SYSSPACE,
634                              NLC_LOCKVP | NLC_CREATE | NLC_REFDVP);
635         if (error == 0)
636                 error = nlookup(&nd);
637         if (error == 0 && nd.nl_nch.ncp->nc_vp != NULL)
638                 error = EADDRINUSE;
639         if (error)
640                 goto done;
641
642         VATTR_NULL(&vattr);
643         vattr.va_type = VSOCK;
644         vattr.va_mode = (ACCESSPERMS & ~p->p_fd->fd_cmask);
645         error = VOP_NCREATE(&nd.nl_nch, nd.nl_dvp, &vp, nd.nl_cred, &vattr);
646         if (error == 0) {
647                 vp->v_socket = unp->unp_socket;
648                 unp->unp_vnode = vp;
649                 unp->unp_addr = (struct sockaddr_un *)dup_sockaddr(nam);
650                 vn_unlock(vp);
651         }
652 done:
653         nlookup_done(&nd);
654         return (error);
655 }
656
657 static int
658 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
659 {
660         struct proc *p = td->td_proc;
661         struct sockaddr_un *soun = (struct sockaddr_un *)nam;
662         struct vnode *vp;
663         struct socket *so2, *so3;
664         struct unpcb *unp, *unp2, *unp3;
665         int error, len;
666         struct nlookupdata nd;
667         char buf[SOCK_MAXADDRLEN];
668
669         KKASSERT(p);
670
671         len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
672         if (len <= 0)
673                 return EINVAL;
674         strncpy(buf, soun->sun_path, len);
675         buf[len] = 0;
676
677         vp = NULL;
678         error = nlookup_init(&nd, buf, UIO_SYSSPACE, NLC_FOLLOW);
679         if (error == 0)
680                 error = nlookup(&nd);
681         if (error == 0)
682                 error = cache_vget(&nd.nl_nch, nd.nl_cred, LK_EXCLUSIVE, &vp);
683         nlookup_done(&nd);
684         if (error)
685                 return (error);
686
687         if (vp->v_type != VSOCK) {
688                 error = ENOTSOCK;
689                 goto bad;
690         }
691         error = VOP_ACCESS(vp, VWRITE, p->p_ucred);
692         if (error)
693                 goto bad;
694         so2 = vp->v_socket;
695         if (so2 == NULL) {
696                 error = ECONNREFUSED;
697                 goto bad;
698         }
699         if (so->so_type != so2->so_type) {
700                 error = EPROTOTYPE;
701                 goto bad;
702         }
703         if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
704                 if (!(so2->so_options & SO_ACCEPTCONN) ||
705                     (so3 = sonewconn(so2, 0)) == NULL) {
706                         error = ECONNREFUSED;
707                         goto bad;
708                 }
709                 unp = so->so_pcb;
710                 unp2 = so2->so_pcb;
711                 unp3 = so3->so_pcb;
712                 if (unp2->unp_addr)
713                         unp3->unp_addr = (struct sockaddr_un *)
714                                 dup_sockaddr((struct sockaddr *)unp2->unp_addr);
715
716                 /*
717                  * unp_peercred management:
718                  *
719                  * The connecter's (client's) credentials are copied
720                  * from its process structure at the time of connect()
721                  * (which is now).
722                  */
723                 cru2x(p->p_ucred, &unp3->unp_peercred);
724                 unp3->unp_flags |= UNP_HAVEPC;
725                 /*
726                  * The receiver's (server's) credentials are copied
727                  * from the unp_peercred member of socket on which the
728                  * former called listen(); unp_listen() cached that
729                  * process's credentials at that time so we can use
730                  * them now.
731                  */
732                 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
733                     ("unp_connect: listener without cached peercred"));
734                 memcpy(&unp->unp_peercred, &unp2->unp_peercred,
735                     sizeof(unp->unp_peercred));
736                 unp->unp_flags |= UNP_HAVEPC;
737
738                 so2 = so3;
739         }
740         error = unp_connect2(so, so2);
741 bad:
742         vput(vp);
743         return (error);
744 }
745
746 int
747 unp_connect2(struct socket *so, struct socket *so2)
748 {
749         struct unpcb *unp = so->so_pcb;
750         struct unpcb *unp2;
751
752         if (so2->so_type != so->so_type)
753                 return (EPROTOTYPE);
754         unp2 = so2->so_pcb;
755         unp->unp_conn = unp2;
756         switch (so->so_type) {
757
758         case SOCK_DGRAM:
759                 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
760                 soisconnected(so);
761                 break;
762
763         case SOCK_STREAM:
764         case SOCK_SEQPACKET:
765                 unp2->unp_conn = unp;
766                 soisconnected(so);
767                 soisconnected(so2);
768                 break;
769
770         default:
771                 panic("unp_connect2");
772         }
773         return (0);
774 }
775
776 static void
777 unp_disconnect(struct unpcb *unp)
778 {
779         struct unpcb *unp2 = unp->unp_conn;
780
781         if (unp2 == NULL)
782                 return;
783
784         unp->unp_conn = NULL;
785
786         switch (unp->unp_socket->so_type) {
787         case SOCK_DGRAM:
788                 LIST_REMOVE(unp, unp_reflink);
789                 unp->unp_socket->so_state &= ~SS_ISCONNECTED;
790                 break;
791         case SOCK_STREAM:
792         case SOCK_SEQPACKET:
793                 soisdisconnected(unp->unp_socket);
794                 unp2->unp_conn = NULL;
795                 soisdisconnected(unp2->unp_socket);
796                 break;
797         }
798 }
799
800 #ifdef notdef
801 void
802 unp_abort(struct unpcb *unp)
803 {
804
805         unp_detach(unp);
806 }
807 #endif
808
809 static int
810 prison_unpcb(struct thread *td, struct unpcb *unp)
811 {
812         struct proc *p;
813
814         if (td == NULL)
815                 return (0);
816         if ((p = td->td_proc) == NULL)
817                 return (0);
818         if (!p->p_ucred->cr_prison)
819                 return (0);
820         if (p->p_fd->fd_rdir == unp->unp_rvnode)
821                 return (0);
822         return (1);
823 }
824
825 static int
826 unp_pcblist(SYSCTL_HANDLER_ARGS)
827 {
828         int error, i, n;
829         struct unpcb *unp, **unp_list;
830         unp_gen_t gencnt;
831         struct unp_head *head;
832
833         head = ((intptr_t)arg1 == SOCK_DGRAM ? &unp_dhead : &unp_shead);
834
835         KKASSERT(curproc != NULL);
836
837         /*
838          * The process of preparing the PCB list is too time-consuming and
839          * resource-intensive to repeat twice on every request.
840          */
841         if (req->oldptr == NULL) {
842                 n = unp_count;
843                 req->oldidx = (n + n/8) * sizeof(struct xunpcb);
844                 return 0;
845         }
846
847         if (req->newptr != NULL)
848                 return EPERM;
849
850         /*
851          * OK, now we're committed to doing something.
852          */
853         gencnt = unp_gencnt;
854         n = unp_count;
855
856         unp_list = kmalloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
857         
858         for (unp = LIST_FIRST(head), i = 0; unp && i < n;
859              unp = LIST_NEXT(unp, unp_link)) {
860                 if (unp->unp_gencnt <= gencnt && !prison_unpcb(req->td, unp))
861                         unp_list[i++] = unp;
862         }
863         n = i;                  /* in case we lost some during malloc */
864
865         error = 0;
866         for (i = 0; i < n; i++) {
867                 unp = unp_list[i];
868                 if (unp->unp_gencnt <= gencnt) {
869                         struct xunpcb xu;
870                         xu.xu_len = sizeof xu;
871                         xu.xu_unpp = unp;
872                         /*
873                          * XXX - need more locking here to protect against
874                          * connect/disconnect races for SMP.
875                          */
876                         if (unp->unp_addr)
877                                 bcopy(unp->unp_addr, &xu.xu_addr, 
878                                       unp->unp_addr->sun_len);
879                         if (unp->unp_conn && unp->unp_conn->unp_addr)
880                                 bcopy(unp->unp_conn->unp_addr,
881                                       &xu.xu_caddr,
882                                       unp->unp_conn->unp_addr->sun_len);
883                         bcopy(unp, &xu.xu_unp, sizeof *unp);
884                         sotoxsocket(unp->unp_socket, &xu.xu_socket);
885                         error = SYSCTL_OUT(req, &xu, sizeof xu);
886                 }
887         }
888         kfree(unp_list, M_TEMP);
889         return error;
890 }
891
892 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD, 
893             (caddr_t)(long)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
894             "List of active local datagram sockets");
895 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD, 
896             (caddr_t)(long)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
897             "List of active local stream sockets");
898 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist, CTLFLAG_RD, 
899             (caddr_t)(long)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
900             "List of active local seqpacket stream sockets");
901
902 static void
903 unp_shutdown(struct unpcb *unp)
904 {
905         struct socket *so;
906
907         if ((unp->unp_socket->so_type == SOCK_STREAM ||
908              unp->unp_socket->so_type == SOCK_SEQPACKET) &&
909             unp->unp_conn != NULL && (so = unp->unp_conn->unp_socket)) {
910                 socantrcvmore(so);
911         }
912 }
913
914 static void
915 unp_drop(struct unpcb *unp, int err)
916 {
917         struct socket *so = unp->unp_socket;
918
919         so->so_error = err;
920         unp_disconnect(unp);
921 }
922
923 #ifdef notdef
924 void
925 unp_drain(void)
926 {
927
928 }
929 #endif
930
931 int
932 unp_externalize(struct mbuf *rights)
933 {
934         struct proc *p = curproc;               /* XXX */
935         int i;
936         struct cmsghdr *cm = mtod(rights, struct cmsghdr *);
937         int *fdp;
938         struct file **rp;
939         struct file *fp;
940         int newfds = (cm->cmsg_len - (CMSG_DATA(cm) - (u_char *)cm))
941                 / sizeof (struct file *);
942         int f;
943
944         /*
945          * if the new FD's will not fit, then we free them all
946          */
947         if (!fdavail(p, newfds)) {
948                 rp = (struct file **)CMSG_DATA(cm);
949                 for (i = 0; i < newfds; i++) {
950                         fp = *rp;
951                         /*
952                          * zero the pointer before calling unp_discard,
953                          * since it may end up in unp_gc()..
954                          */
955                         *rp++ = 0;
956                         unp_discard(fp, NULL);
957                 }
958                 return (EMSGSIZE);
959         }
960
961         /*
962          * now change each pointer to an fd in the global table to 
963          * an integer that is the index to the local fd table entry
964          * that we set up to point to the global one we are transferring.
965          * If sizeof (struct file *) is bigger than or equal to sizeof int,
966          * then do it in forward order. In that case, an integer will
967          * always come in the same place or before its corresponding
968          * struct file pointer.
969          * If sizeof (struct file *) is smaller than sizeof int, then
970          * do it in reverse order.
971          */
972         if (sizeof (struct file *) >= sizeof (int)) {
973                 fdp = (int *)(cm + 1);
974                 rp = (struct file **)CMSG_DATA(cm);
975                 for (i = 0; i < newfds; i++) {
976                         if (fdalloc(p, 0, &f))
977                                 panic("unp_externalize");
978                         fp = *rp++;
979                         unp_fp_externalize(p, fp, f);
980                         *fdp++ = f;
981                 }
982         } else {
983                 fdp = (int *)(cm + 1) + newfds - 1;
984                 rp = (struct file **)CMSG_DATA(cm) + newfds - 1;
985                 for (i = 0; i < newfds; i++) {
986                         if (fdalloc(p, 0, &f))
987                                 panic("unp_externalize");
988                         fp = *rp--;
989                         unp_fp_externalize(p, fp, f);
990                         *fdp-- = f;
991                 }
992         }
993
994         /*
995          * Adjust length, in case sizeof(struct file *) and sizeof(int)
996          * differs.
997          */
998         cm->cmsg_len = CMSG_LEN(newfds * sizeof(int));
999         rights->m_len = cm->cmsg_len;
1000         return (0);
1001 }
1002
1003 static void
1004 unp_fp_externalize(struct proc *p, struct file *fp, int fd)
1005 {
1006         struct file *fx;
1007         int error;
1008
1009         if (p) {
1010                 KKASSERT(fd >= 0);
1011                 if (fp->f_flag & FREVOKED) {
1012                         kprintf("Warning: revoked fp exiting unix socket\n");
1013                         fx = NULL;
1014                         error = falloc(p, &fx, NULL);
1015                         if (error == 0)
1016                                 fsetfd(p, fx, fd);
1017                         else
1018                                 fsetfd(p, NULL, fd);
1019                         fdrop(fx);
1020                 } else {
1021                         fsetfd(p, fp, fd);
1022                 }
1023         }
1024         spin_lock_wr(&unp_spin);
1025         fp->f_msgcount--;
1026         unp_rights--;
1027         spin_unlock_wr(&unp_spin);
1028         fdrop(fp);
1029 }
1030
1031
1032 void
1033 unp_init(void)
1034 {
1035         LIST_INIT(&unp_dhead);
1036         LIST_INIT(&unp_shead);
1037         spin_init(&unp_spin);
1038 }
1039
1040 static int
1041 unp_internalize(struct mbuf *control, struct thread *td)
1042 {
1043         struct proc *p = td->td_proc;
1044         struct filedesc *fdescp;
1045         struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1046         struct file **rp;
1047         struct file *fp;
1048         int i, fd, *fdp;
1049         struct cmsgcred *cmcred;
1050         int oldfds;
1051         u_int newlen;
1052
1053         KKASSERT(p);
1054         fdescp = p->p_fd;
1055         if ((cm->cmsg_type != SCM_RIGHTS && cm->cmsg_type != SCM_CREDS) ||
1056             cm->cmsg_level != SOL_SOCKET || cm->cmsg_len != control->m_len)
1057                 return (EINVAL);
1058
1059         /*
1060          * Fill in credential information.
1061          */
1062         if (cm->cmsg_type == SCM_CREDS) {
1063                 cmcred = (struct cmsgcred *)(cm + 1);
1064                 cmcred->cmcred_pid = p->p_pid;
1065                 cmcred->cmcred_uid = p->p_ucred->cr_ruid;
1066                 cmcred->cmcred_gid = p->p_ucred->cr_rgid;
1067                 cmcred->cmcred_euid = p->p_ucred->cr_uid;
1068                 cmcred->cmcred_ngroups = MIN(p->p_ucred->cr_ngroups,
1069                                                         CMGROUP_MAX);
1070                 for (i = 0; i < cmcred->cmcred_ngroups; i++)
1071                         cmcred->cmcred_groups[i] = p->p_ucred->cr_groups[i];
1072                 return(0);
1073         }
1074
1075         oldfds = (cm->cmsg_len - sizeof (*cm)) / sizeof (int);
1076         /*
1077          * check that all the FDs passed in refer to legal OPEN files
1078          * If not, reject the entire operation.
1079          */
1080         fdp = (int *)(cm + 1);
1081         for (i = 0; i < oldfds; i++) {
1082                 fd = *fdp++;
1083                 if ((unsigned)fd >= fdescp->fd_nfiles ||
1084                     fdescp->fd_files[fd].fp == NULL)
1085                         return (EBADF);
1086                 if (fdescp->fd_files[fd].fp->f_type == DTYPE_KQUEUE)
1087                         return (EOPNOTSUPP);
1088         }
1089         /*
1090          * Now replace the integer FDs with pointers to
1091          * the associated global file table entry..
1092          * Allocate a bigger buffer as necessary. But if an cluster is not
1093          * enough, return E2BIG.
1094          */
1095         newlen = CMSG_LEN(oldfds * sizeof(struct file *));
1096         if (newlen > MCLBYTES)
1097                 return (E2BIG);
1098         if (newlen - control->m_len > M_TRAILINGSPACE(control)) {
1099                 if (control->m_flags & M_EXT)
1100                         return (E2BIG);
1101                 MCLGET(control, MB_WAIT);
1102                 if (!(control->m_flags & M_EXT))
1103                         return (ENOBUFS);
1104
1105                 /* copy the data to the cluster */
1106                 memcpy(mtod(control, char *), cm, cm->cmsg_len);
1107                 cm = mtod(control, struct cmsghdr *);
1108         }
1109
1110         /*
1111          * Adjust length, in case sizeof(struct file *) and sizeof(int)
1112          * differs.
1113          */
1114         control->m_len = cm->cmsg_len = newlen;
1115
1116         /*
1117          * Transform the file descriptors into struct file pointers.
1118          * If sizeof (struct file *) is bigger than or equal to sizeof int,
1119          * then do it in reverse order so that the int won't get until
1120          * we're done.
1121          * If sizeof (struct file *) is smaller than sizeof int, then
1122          * do it in forward order.
1123          */
1124         if (sizeof (struct file *) >= sizeof (int)) {
1125                 fdp = (int *)(cm + 1) + oldfds - 1;
1126                 rp = (struct file **)CMSG_DATA(cm) + oldfds - 1;
1127                 for (i = 0; i < oldfds; i++) {
1128                         fp = fdescp->fd_files[*fdp--].fp;
1129                         *rp-- = fp;
1130                         fhold(fp);
1131                         spin_lock_wr(&unp_spin);
1132                         fp->f_msgcount++;
1133                         unp_rights++;
1134                         spin_unlock_wr(&unp_spin);
1135                 }
1136         } else {
1137                 fdp = (int *)(cm + 1);
1138                 rp = (struct file **)CMSG_DATA(cm);
1139                 for (i = 0; i < oldfds; i++) {
1140                         fp = fdescp->fd_files[*fdp++].fp;
1141                         *rp++ = fp;
1142                         fhold(fp);
1143                         spin_lock_wr(&unp_spin);
1144                         fp->f_msgcount++;
1145                         unp_rights++;
1146                         spin_unlock_wr(&unp_spin);
1147                 }
1148         }
1149         return (0);
1150 }
1151
1152 /*
1153  * Garbage collect in-transit file descriptors that get lost due to
1154  * loops (i.e. when a socket is sent to another process over itself,
1155  * and more complex situations).
1156  *
1157  * NOT MPSAFE - TODO socket flush code and maybe closef.  Rest is MPSAFE.
1158  */
1159
1160 struct unp_gc_info {
1161         struct file **extra_ref;
1162         struct file *locked_fp;
1163         int defer;
1164         int index;
1165         int maxindex;
1166 };
1167
1168 static void
1169 unp_gc(void)
1170 {
1171         struct unp_gc_info info;
1172         static boolean_t unp_gcing;
1173         struct file **fpp;
1174         int i;
1175
1176         spin_lock_wr(&unp_spin);
1177         if (unp_gcing) {
1178                 spin_unlock_wr(&unp_spin);
1179                 return;
1180         }
1181         unp_gcing = TRUE;
1182         spin_unlock_wr(&unp_spin);
1183
1184         /* 
1185          * before going through all this, set all FDs to 
1186          * be NOT defered and NOT externally accessible
1187          */
1188         info.defer = 0;
1189         allfiles_scan_exclusive(unp_gc_clearmarks, NULL);
1190         do {
1191                 allfiles_scan_exclusive(unp_gc_checkmarks, &info);
1192         } while (info.defer);
1193
1194         /*
1195          * We grab an extra reference to each of the file table entries
1196          * that are not otherwise accessible and then free the rights
1197          * that are stored in messages on them.
1198          *
1199          * The bug in the orginal code is a little tricky, so I'll describe
1200          * what's wrong with it here.
1201          *
1202          * It is incorrect to simply unp_discard each entry for f_msgcount
1203          * times -- consider the case of sockets A and B that contain
1204          * references to each other.  On a last close of some other socket,
1205          * we trigger a gc since the number of outstanding rights (unp_rights)
1206          * is non-zero.  If during the sweep phase the gc code un_discards,
1207          * we end up doing a (full) closef on the descriptor.  A closef on A
1208          * results in the following chain.  Closef calls soo_close, which
1209          * calls soclose.   Soclose calls first (through the switch
1210          * uipc_usrreq) unp_detach, which re-invokes unp_gc.  Unp_gc simply
1211          * returns because the previous instance had set unp_gcing, and
1212          * we return all the way back to soclose, which marks the socket
1213          * with SS_NOFDREF, and then calls sofree.  Sofree calls sorflush
1214          * to free up the rights that are queued in messages on the socket A,
1215          * i.e., the reference on B.  The sorflush calls via the dom_dispose
1216          * switch unp_dispose, which unp_scans with unp_discard.  This second
1217          * instance of unp_discard just calls closef on B.
1218          *
1219          * Well, a similar chain occurs on B, resulting in a sorflush on B,
1220          * which results in another closef on A.  Unfortunately, A is already
1221          * being closed, and the descriptor has already been marked with
1222          * SS_NOFDREF, and soclose panics at this point.
1223          *
1224          * Here, we first take an extra reference to each inaccessible
1225          * descriptor.  Then, we call sorflush ourself, since we know
1226          * it is a Unix domain socket anyhow.  After we destroy all the
1227          * rights carried in messages, we do a last closef to get rid
1228          * of our extra reference.  This is the last close, and the
1229          * unp_detach etc will shut down the socket.
1230          *
1231          * 91/09/19, bsy@cs.cmu.edu
1232          */
1233         info.extra_ref = kmalloc(256 * sizeof(struct file *), M_FILE, M_WAITOK);
1234         info.maxindex = 256;
1235
1236         do {
1237                 /*
1238                  * Look for matches
1239                  */
1240                 info.index = 0;
1241                 allfiles_scan_exclusive(unp_gc_checkrefs, &info);
1242
1243                 /* 
1244                  * For each FD on our hit list, do the following two things
1245                  */
1246                 for (i = info.index, fpp = info.extra_ref; --i >= 0; ++fpp) {
1247                         struct file *tfp = *fpp;
1248                         if (tfp->f_type == DTYPE_SOCKET && tfp->f_data != NULL)
1249                                 sorflush((struct socket *)(tfp->f_data));
1250                 }
1251                 for (i = info.index, fpp = info.extra_ref; --i >= 0; ++fpp)
1252                         closef(*fpp, NULL);
1253         } while (info.index == info.maxindex);
1254         kfree((caddr_t)info.extra_ref, M_FILE);
1255         unp_gcing = FALSE;
1256 }
1257
1258 /*
1259  * MPSAFE - NOTE: filehead list and file pointer spinlocked on entry
1260  */
1261 static int
1262 unp_gc_checkrefs(struct file *fp, void *data)
1263 {
1264         struct unp_gc_info *info = data;
1265
1266         if (fp->f_count == 0)
1267                 return(0);
1268         if (info->index == info->maxindex)
1269                 return(-1);
1270
1271         /* 
1272          * If all refs are from msgs, and it's not marked accessible
1273          * then it must be referenced from some unreachable cycle
1274          * of (shut-down) FDs, so include it in our
1275          * list of FDs to remove
1276          */
1277         if (fp->f_count == fp->f_msgcount && !(fp->f_flag & FMARK)) {
1278                 info->extra_ref[info->index++] = fp;
1279                 fhold(fp);
1280         }
1281         return(0);
1282 }
1283
1284 /*
1285  * MPSAFE - NOTE: filehead list and file pointer spinlocked on entry
1286  */
1287 static int
1288 unp_gc_clearmarks(struct file *fp, void *data __unused)
1289 {
1290         atomic_clear_int(&fp->f_flag, FMARK | FDEFER);
1291         return(0);
1292 }
1293
1294 /*
1295  * MPSAFE - NOTE: filehead list and file pointer spinlocked on entry
1296  */
1297 static int
1298 unp_gc_checkmarks(struct file *fp, void *data)
1299 {
1300         struct unp_gc_info *info = data;
1301         struct socket *so;
1302
1303         /*
1304          * If the file is not open, skip it
1305          */
1306         if (fp->f_count == 0)
1307                 return(0);
1308         /*
1309          * If we already marked it as 'defer'  in a
1310          * previous pass, then try process it this time
1311          * and un-mark it
1312          */
1313         if (fp->f_flag & FDEFER) {
1314                 atomic_clear_int(&fp->f_flag, FDEFER);
1315                 --info->defer;
1316         } else {
1317                 /*
1318                  * if it's not defered, then check if it's
1319                  * already marked.. if so skip it
1320                  */
1321                 if (fp->f_flag & FMARK)
1322                         return(0);
1323                 /* 
1324                  * If all references are from messages
1325                  * in transit, then skip it. it's not 
1326                  * externally accessible.
1327                  */ 
1328                 if (fp->f_count == fp->f_msgcount)
1329                         return(0);
1330                 /* 
1331                  * If it got this far then it must be
1332                  * externally accessible.
1333                  */
1334                 atomic_set_int(&fp->f_flag, FMARK);
1335         }
1336
1337         /*
1338          * either it was defered, or it is externally 
1339          * accessible and not already marked so.
1340          * Now check if it is possibly one of OUR sockets.
1341          */ 
1342         if (fp->f_type != DTYPE_SOCKET ||
1343             (so = (struct socket *)fp->f_data) == NULL)
1344                 return(0);
1345         if (so->so_proto->pr_domain != &localdomain ||
1346             !(so->so_proto->pr_flags & PR_RIGHTS))
1347                 return(0);
1348 #ifdef notdef
1349         if (so->so_rcv.sb_flags & SB_LOCK) {
1350                 /*
1351                  * This is problematical; it's not clear
1352                  * we need to wait for the sockbuf to be
1353                  * unlocked (on a uniprocessor, at least),
1354                  * and it's also not clear what to do
1355                  * if sbwait returns an error due to receipt
1356                  * of a signal.  If sbwait does return
1357                  * an error, we'll go into an infinite
1358                  * loop.  Delete all of this for now.
1359                  */
1360                 sbwait(&so->so_rcv);
1361                 goto restart;
1362         }
1363 #endif
1364         /*
1365          * So, Ok, it's one of our sockets and it IS externally
1366          * accessible (or was defered). Now we look
1367          * to see if we hold any file descriptors in its
1368          * message buffers. Follow those links and mark them 
1369          * as accessible too.
1370          */
1371         info->locked_fp = fp;
1372 /*      spin_lock_wr(&so->so_rcv.sb_spin); */
1373         unp_scan(so->so_rcv.ssb_mb, unp_mark, info);
1374 /*      spin_unlock_wr(&so->so_rcv.sb_spin);*/
1375         return (0);
1376 }
1377
1378 /*
1379  * Scan all unix domain sockets and replace any revoked file pointers
1380  * found with the dummy file pointer fx.  We don't worry about races
1381  * against file pointers being read out as those are handled in the
1382  * externalize code.
1383  */
1384
1385 #define REVOKE_GC_MAXFILES      32
1386
1387 struct unp_revoke_gc_info {
1388         struct file     *fx;
1389         struct file     *fary[REVOKE_GC_MAXFILES];
1390         int             fcount;
1391 };
1392
1393 void
1394 unp_revoke_gc(struct file *fx)
1395 {
1396         struct unp_revoke_gc_info info;
1397         int i;
1398
1399         info.fx = fx;
1400         do {
1401                 info.fcount = 0;
1402                 allfiles_scan_exclusive(unp_revoke_gc_check, &info);
1403                 for (i = 0; i < info.fcount; ++i)
1404                         unp_fp_externalize(NULL, info.fary[i], -1);
1405         } while (info.fcount == REVOKE_GC_MAXFILES);
1406 }
1407
1408 /*
1409  * Check for and replace revoked descriptors.
1410  *
1411  * WARNING:  This routine is not allowed to block.
1412  */
1413 static int
1414 unp_revoke_gc_check(struct file *fps, void *vinfo)
1415 {
1416         struct unp_revoke_gc_info *info = vinfo;
1417         struct file *fp;
1418         struct socket *so;
1419         struct mbuf *m0;
1420         struct mbuf *m;
1421         struct file **rp;
1422         struct cmsghdr *cm;
1423         int i;
1424         int qfds;
1425
1426         /*
1427          * Is this a unix domain socket with rights-passing abilities?
1428          */
1429         if (fps->f_type != DTYPE_SOCKET)
1430                 return (0);
1431         if ((so = (struct socket *)fps->f_data) == NULL)
1432                 return(0);
1433         if (so->so_proto->pr_domain != &localdomain)
1434                 return(0);
1435         if ((so->so_proto->pr_flags & PR_RIGHTS) == 0)
1436                 return(0);
1437
1438         /*
1439          * Scan the mbufs for control messages and replace any revoked
1440          * descriptors we find.
1441          */
1442         m0 = so->so_rcv.ssb_mb;
1443         while (m0) {
1444                 for (m = m0; m; m = m->m_next) {
1445                         if (m->m_type != MT_CONTROL)
1446                                 continue;
1447                         if (m->m_len < sizeof(*cm))
1448                                 continue;
1449                         cm = mtod(m, struct cmsghdr *);
1450                         if (cm->cmsg_level != SOL_SOCKET ||
1451                             cm->cmsg_type != SCM_RIGHTS) {
1452                                 continue;
1453                         }
1454                         qfds = (cm->cmsg_len -
1455                                 (CMSG_DATA(cm) - (u_char *)cm))
1456                                         / sizeof (struct file *);
1457                         rp = (struct file **)CMSG_DATA(cm);
1458                         for (i = 0; i < qfds; i++) {
1459                                 fp = rp[i];
1460                                 if (fp->f_flag & FREVOKED) {
1461                                         kprintf("Warning: Removing revoked fp from unix domain socket queue\n");
1462                                         fhold(info->fx);
1463                                         info->fx->f_msgcount++;
1464                                         unp_rights++;
1465                                         rp[i] = info->fx;
1466                                         info->fary[info->fcount++] = fp;
1467                                 }
1468                                 if (info->fcount == REVOKE_GC_MAXFILES)
1469                                         break;
1470                         }
1471                         if (info->fcount == REVOKE_GC_MAXFILES)
1472                                 break;
1473                 }
1474                 m0 = m0->m_nextpkt;
1475                 if (info->fcount == REVOKE_GC_MAXFILES)
1476                         break;
1477         }
1478
1479         /*
1480          * Stop the scan if we filled up our array.
1481          */
1482         if (info->fcount == REVOKE_GC_MAXFILES)
1483                 return(-1);
1484         return(0);
1485 }
1486
1487 void
1488 unp_dispose(struct mbuf *m)
1489 {
1490         if (m)
1491                 unp_scan(m, unp_discard, NULL);
1492 }
1493
1494 static int
1495 unp_listen(struct unpcb *unp, struct thread *td)
1496 {
1497         struct proc *p = td->td_proc;
1498
1499         KKASSERT(p);
1500         cru2x(p->p_ucred, &unp->unp_peercred);
1501         unp->unp_flags |= UNP_HAVEPCCACHED;
1502         return (0);
1503 }
1504
1505 static void
1506 unp_scan(struct mbuf *m0, void (*op)(struct file *, void *), void *data)
1507 {
1508         struct mbuf *m;
1509         struct file **rp;
1510         struct cmsghdr *cm;
1511         int i;
1512         int qfds;
1513
1514         while (m0) {
1515                 for (m = m0; m; m = m->m_next) {
1516                         if (m->m_type == MT_CONTROL &&
1517                             m->m_len >= sizeof(*cm)) {
1518                                 cm = mtod(m, struct cmsghdr *);
1519                                 if (cm->cmsg_level != SOL_SOCKET ||
1520                                     cm->cmsg_type != SCM_RIGHTS)
1521                                         continue;
1522                                 qfds = (cm->cmsg_len -
1523                                         (CMSG_DATA(cm) - (u_char *)cm))
1524                                                 / sizeof (struct file *);
1525                                 rp = (struct file **)CMSG_DATA(cm);
1526                                 for (i = 0; i < qfds; i++)
1527                                         (*op)(*rp++, data);
1528                                 break;          /* XXX, but saves time */
1529                         }
1530                 }
1531                 m0 = m0->m_nextpkt;
1532         }
1533 }
1534
1535 static void
1536 unp_mark(struct file *fp, void *data)
1537 {
1538         struct unp_gc_info *info = data;
1539
1540         if ((fp->f_flag & FMARK) == 0) {
1541                 ++info->defer;
1542                 atomic_set_int(&fp->f_flag, FMARK | FDEFER);
1543         }
1544 }
1545
1546 static void
1547 unp_discard(struct file *fp, void *data __unused)
1548 {
1549         spin_lock_wr(&unp_spin);
1550         fp->f_msgcount--;
1551         unp_rights--;
1552         spin_unlock_wr(&unp_spin);
1553         closef(fp, NULL);
1554 }
1555