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