Merge from vendor branch NTPD:
[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.16 2004/10/12 19:20:46 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/namei.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/sysctl.h>
55 #include <sys/un.h>
56 #include <sys/unpcb.h>
57 #include <sys/vnode.h>
58 #include <sys/file2.h>
59
60 #include <vm/vm_zone.h>
61
62 static  struct vm_zone *unp_zone;
63 static  unp_gen_t unp_gencnt;
64 static  u_int unp_count;
65
66 static  struct unp_head unp_shead, unp_dhead;
67
68 /*
69  * Unix communications domain.
70  *
71  * TODO:
72  *      SEQPACKET, RDM
73  *      rethink name space problems
74  *      need a proper out-of-band
75  *      lock pushdown
76  */
77 static struct   sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
78 static ino_t    unp_ino;                /* prototype for fake inode numbers */
79
80 static int     unp_attach (struct socket *, struct pru_attach_info *);
81 static void    unp_detach (struct unpcb *);
82 static int     unp_bind (struct unpcb *,struct sockaddr *, struct thread *);
83 static int     unp_connect (struct socket *,struct sockaddr *,
84                                 struct thread *);
85 static void    unp_disconnect (struct unpcb *);
86 static void    unp_shutdown (struct unpcb *);
87 static void    unp_drop (struct unpcb *, int);
88 static void    unp_gc (void);
89 static void    unp_scan (struct mbuf *, void (*)(struct file *));
90 static void    unp_mark (struct file *);
91 static void    unp_discard (struct file *);
92 static int     unp_internalize (struct mbuf *, struct thread *);
93 static int     unp_listen (struct unpcb *, struct thread *);
94
95 static int
96 uipc_abort(struct socket *so)
97 {
98         struct unpcb *unp = sotounpcb(so);
99
100         if (unp == 0)
101                 return EINVAL;
102         unp_drop(unp, ECONNABORTED);
103         unp_detach(unp);
104         sofree(so);
105         return 0;
106 }
107
108 static int
109 uipc_accept(struct socket *so, struct sockaddr **nam)
110 {
111         struct unpcb *unp = sotounpcb(so);
112
113         if (unp == 0)
114                 return EINVAL;
115
116         /*
117          * Pass back name of connected socket,
118          * if it was bound and we are still connected
119          * (our peer may have closed already!).
120          */
121         if (unp->unp_conn && unp->unp_conn->unp_addr) {
122                 *nam = dup_sockaddr((struct sockaddr *)unp->unp_conn->unp_addr);
123         } else {
124                 *nam = dup_sockaddr((struct sockaddr *)&sun_noname);
125         }
126         return 0;
127 }
128
129 static int
130 uipc_attach(struct socket *so, int proto, struct pru_attach_info *ai)
131 {
132         struct unpcb *unp = sotounpcb(so);
133
134         if (unp != 0)
135                 return EISCONN;
136         return unp_attach(so, ai);
137 }
138
139 static int
140 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
141 {
142         struct unpcb *unp = sotounpcb(so);
143
144         if (unp == 0)
145                 return EINVAL;
146         return unp_bind(unp, nam, td);
147 }
148
149 static int
150 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
151 {
152         struct unpcb *unp = sotounpcb(so);
153
154         if (unp == 0)
155                 return EINVAL;
156         return unp_connect(so, nam, td);
157 }
158
159 static int
160 uipc_connect2(struct socket *so1, struct socket *so2)
161 {
162         struct unpcb *unp = sotounpcb(so1);
163
164         if (unp == 0)
165                 return EINVAL;
166
167         return unp_connect2(so1, so2);
168 }
169
170 /* control is EOPNOTSUPP */
171
172 static int
173 uipc_detach(struct socket *so)
174 {
175         struct unpcb *unp = sotounpcb(so);
176
177         if (unp == 0)
178                 return EINVAL;
179
180         unp_detach(unp);
181         return 0;
182 }
183
184 static int
185 uipc_disconnect(struct socket *so)
186 {
187         struct unpcb *unp = sotounpcb(so);
188
189         if (unp == 0)
190                 return EINVAL;
191         unp_disconnect(unp);
192         return 0;
193 }
194
195 static int
196 uipc_listen(struct socket *so, struct thread *td)
197 {
198         struct unpcb *unp = sotounpcb(so);
199
200         if (unp == 0 || unp->unp_vnode == 0)
201                 return EINVAL;
202         return unp_listen(unp, td);
203 }
204
205 static int
206 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
207 {
208         struct unpcb *unp = sotounpcb(so);
209
210         if (unp == 0)
211                 return EINVAL;
212         if (unp->unp_conn && unp->unp_conn->unp_addr)
213                 *nam = dup_sockaddr((struct sockaddr *)unp->unp_conn->unp_addr);
214         else {
215                 /*
216                  * XXX: It seems that this test always fails even when
217                  * connection is established.  So, this else clause is
218                  * added as workaround to return PF_LOCAL sockaddr.
219                  */
220                 *nam = dup_sockaddr((struct sockaddr *)&sun_noname);
221         }
222         return 0;
223 }
224
225 static int
226 uipc_rcvd(struct socket *so, int flags)
227 {
228         struct unpcb *unp = sotounpcb(so);
229         struct socket *so2;
230         u_long newhiwat;
231
232         if (unp == 0)
233                 return EINVAL;
234         switch (so->so_type) {
235         case SOCK_DGRAM:
236                 panic("uipc_rcvd DGRAM?");
237                 /*NOTREACHED*/
238
239         case SOCK_STREAM:
240                 if (unp->unp_conn == 0)
241                         break;
242                 so2 = unp->unp_conn->unp_socket;
243                 /*
244                  * Adjust backpressure on sender
245                  * and wakeup any waiting to write.
246                  */
247                 so2->so_snd.sb_mbmax += unp->unp_mbcnt - so->so_rcv.sb_mbcnt;
248                 unp->unp_mbcnt = so->so_rcv.sb_mbcnt;
249                 newhiwat = so2->so_snd.sb_hiwat + unp->unp_cc -
250                     so->so_rcv.sb_cc;
251                 (void)chgsbsize(so2->so_cred->cr_uidinfo, &so2->so_snd.sb_hiwat,
252                     newhiwat, RLIM_INFINITY);
253                 unp->unp_cc = so->so_rcv.sb_cc;
254                 sowwakeup(so2);
255                 break;
256
257         default:
258                 panic("uipc_rcvd unknown socktype");
259         }
260         return 0;
261 }
262
263 /* pru_rcvoob is EOPNOTSUPP */
264
265 static int
266 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
267           struct mbuf *control, struct thread *td)
268 {
269         int error = 0;
270         struct unpcb *unp = sotounpcb(so);
271         struct socket *so2;
272         u_long newhiwat;
273
274         if (unp == 0) {
275                 error = EINVAL;
276                 goto release;
277         }
278         if (flags & PRUS_OOB) {
279                 error = EOPNOTSUPP;
280                 goto release;
281         }
282
283         if (control && (error = unp_internalize(control, td)))
284                 goto release;
285
286         switch (so->so_type) {
287         case SOCK_DGRAM: 
288         {
289                 struct sockaddr *from;
290
291                 if (nam) {
292                         if (unp->unp_conn) {
293                                 error = EISCONN;
294                                 break;
295                         }
296                         error = unp_connect(so, nam, td);
297                         if (error)
298                                 break;
299                 } else {
300                         if (unp->unp_conn == 0) {
301                                 error = ENOTCONN;
302                                 break;
303                         }
304                 }
305                 so2 = unp->unp_conn->unp_socket;
306                 if (unp->unp_addr)
307                         from = (struct sockaddr *)unp->unp_addr;
308                 else
309                         from = &sun_noname;
310                 if (sbappendaddr(&so2->so_rcv, from, m, control)) {
311                         sorwakeup(so2);
312                         m = 0;
313                         control = 0;
314                 } else
315                         error = ENOBUFS;
316                 if (nam)
317                         unp_disconnect(unp);
318                 break;
319         }
320
321         case SOCK_STREAM:
322                 /* Connect if not connected yet. */
323                 /*
324                  * Note: A better implementation would complain
325                  * if not equal to the peer's address.
326                  */
327                 if ((so->so_state & SS_ISCONNECTED) == 0) {
328                         if (nam) {
329                                 error = unp_connect(so, nam, td);
330                                 if (error)
331                                         break;  /* XXX */
332                         } else {
333                                 error = ENOTCONN;
334                                 break;
335                         }
336                 }
337
338                 if (so->so_state & SS_CANTSENDMORE) {
339                         error = EPIPE;
340                         break;
341                 }
342                 if (unp->unp_conn == 0)
343                         panic("uipc_send connected but no connection?");
344                 so2 = unp->unp_conn->unp_socket;
345                 /*
346                  * Send to paired receive port, and then reduce
347                  * send buffer hiwater marks to maintain backpressure.
348                  * Wake up readers.
349                  */
350                 if (control) {
351                         if (sbappendcontrol(&so2->so_rcv, m, control))
352                                 control = 0;
353                 } else
354                         sbappend(&so2->so_rcv, m);
355                 so->so_snd.sb_mbmax -=
356                         so2->so_rcv.sb_mbcnt - unp->unp_conn->unp_mbcnt;
357                 unp->unp_conn->unp_mbcnt = so2->so_rcv.sb_mbcnt;
358                 newhiwat = so->so_snd.sb_hiwat -
359                     (so2->so_rcv.sb_cc - unp->unp_conn->unp_cc);
360                 (void)chgsbsize(so->so_cred->cr_uidinfo, &so->so_snd.sb_hiwat,
361                     newhiwat, RLIM_INFINITY);
362                 unp->unp_conn->unp_cc = so2->so_rcv.sb_cc;
363                 sorwakeup(so2);
364                 m = 0;
365                 break;
366
367         default:
368                 panic("uipc_send unknown socktype");
369         }
370
371         /*
372          * SEND_EOF is equivalent to a SEND followed by
373          * a SHUTDOWN.
374          */
375         if (flags & PRUS_EOF) {
376                 socantsendmore(so);
377                 unp_shutdown(unp);
378         }
379
380         if (control && error != 0)
381                 unp_dispose(control);
382
383 release:
384         if (control)
385                 m_freem(control);
386         if (m)
387                 m_freem(m);
388         return error;
389 }
390
391 static int
392 uipc_sense(struct socket *so, struct stat *sb)
393 {
394         struct unpcb *unp = sotounpcb(so);
395         struct socket *so2;
396
397         if (unp == 0)
398                 return EINVAL;
399         sb->st_blksize = so->so_snd.sb_hiwat;
400         if (so->so_type == SOCK_STREAM && unp->unp_conn != 0) {
401                 so2 = unp->unp_conn->unp_socket;
402                 sb->st_blksize += so2->so_rcv.sb_cc;
403         }
404         sb->st_dev = NOUDEV;
405         if (unp->unp_ino == 0)          /* make up a non-zero inode number */
406                 unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
407         sb->st_ino = unp->unp_ino;
408         return (0);
409 }
410
411 static int
412 uipc_shutdown(struct socket *so)
413 {
414         struct unpcb *unp = sotounpcb(so);
415
416         if (unp == 0)
417                 return EINVAL;
418         socantsendmore(so);
419         unp_shutdown(unp);
420         return 0;
421 }
422
423 static int
424 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
425 {
426         struct unpcb *unp = sotounpcb(so);
427
428         if (unp == 0)
429                 return EINVAL;
430         if (unp->unp_addr)
431                 *nam = dup_sockaddr((struct sockaddr *)unp->unp_addr);
432         return 0;
433 }
434
435 struct pr_usrreqs uipc_usrreqs = {
436         uipc_abort, uipc_accept, uipc_attach, uipc_bind, uipc_connect,
437         uipc_connect2, pru_control_notsupp, uipc_detach, uipc_disconnect,
438         uipc_listen, uipc_peeraddr, uipc_rcvd, pru_rcvoob_notsupp,
439         uipc_send, uipc_sense, uipc_shutdown, uipc_sockaddr,
440         sosend, soreceive, sopoll
441 };
442
443 int
444 uipc_ctloutput(so, sopt)
445         struct socket *so;
446         struct sockopt *sopt;
447 {
448         struct unpcb *unp = sotounpcb(so);
449         int error;
450
451         switch (sopt->sopt_dir) {
452         case SOPT_GET:
453                 switch (sopt->sopt_name) {
454                 case LOCAL_PEERCRED:
455                         if (unp->unp_flags & UNP_HAVEPC)
456                                 error = sooptcopyout(sopt, &unp->unp_peercred,
457                                     sizeof(unp->unp_peercred));
458                         else {
459                                 if (so->so_type == SOCK_STREAM)
460                                         error = ENOTCONN;
461                                 else
462                                         error = EINVAL;
463                         }
464                         break;
465                 default:
466                         error = EOPNOTSUPP;
467                         break;
468                 }
469                 break;
470         case SOPT_SET:
471         default:
472                 error = EOPNOTSUPP;
473                 break;
474         }
475         return (error);
476 }
477         
478 /*
479  * Both send and receive buffers are allocated PIPSIZ bytes of buffering
480  * for stream sockets, although the total for sender and receiver is
481  * actually only PIPSIZ.
482  * Datagram sockets really use the sendspace as the maximum datagram size,
483  * and don't really want to reserve the sendspace.  Their recvspace should
484  * be large enough for at least one max-size datagram plus address.
485  */
486 #ifndef PIPSIZ
487 #define PIPSIZ  8192
488 #endif
489 static u_long   unpst_sendspace = PIPSIZ;
490 static u_long   unpst_recvspace = PIPSIZ;
491 static u_long   unpdg_sendspace = 2*1024;       /* really max datagram size */
492 static u_long   unpdg_recvspace = 4*1024;
493
494 static int      unp_rights;                     /* file descriptors in flight */
495
496 SYSCTL_DECL(_net_local_stream);
497 SYSCTL_INT(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW, 
498            &unpst_sendspace, 0, "");
499 SYSCTL_INT(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
500            &unpst_recvspace, 0, "");
501 SYSCTL_DECL(_net_local_dgram);
502 SYSCTL_INT(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
503            &unpdg_sendspace, 0, "");
504 SYSCTL_INT(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
505            &unpdg_recvspace, 0, "");
506 SYSCTL_DECL(_net_local);
507 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0, "");
508
509 static int
510 unp_attach(struct socket *so, struct pru_attach_info *ai)
511 {
512         struct unpcb *unp;
513         int error;
514
515         if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
516                 switch (so->so_type) {
517
518                 case SOCK_STREAM:
519                         error = soreserve(so, unpst_sendspace, unpst_recvspace,
520                                           ai->sb_rlimit);
521                         break;
522
523                 case SOCK_DGRAM:
524                         error = soreserve(so, unpdg_sendspace, unpdg_recvspace,
525                                           ai->sb_rlimit);
526                         break;
527
528                 default:
529                         panic("unp_attach");
530                 }
531                 if (error)
532                         return (error);
533         }
534         unp = zalloc(unp_zone);
535         if (unp == NULL)
536                 return (ENOBUFS);
537         bzero(unp, sizeof *unp);
538         unp->unp_gencnt = ++unp_gencnt;
539         unp_count++;
540         LIST_INIT(&unp->unp_refs);
541         unp->unp_socket = so;
542         unp->unp_rvnode = ai->fd_rdir;          /* jail cruft XXX JH */
543         LIST_INSERT_HEAD(so->so_type == SOCK_DGRAM ? &unp_dhead
544                          : &unp_shead, unp, unp_link);
545         so->so_pcb = (caddr_t)unp;
546         return (0);
547 }
548
549 static void
550 unp_detach(unp)
551         struct unpcb *unp;
552 {
553         LIST_REMOVE(unp, unp_link);
554         unp->unp_gencnt = ++unp_gencnt;
555         --unp_count;
556         if (unp->unp_vnode) {
557                 unp->unp_vnode->v_socket = 0;
558                 vrele(unp->unp_vnode);
559                 unp->unp_vnode = 0;
560         }
561         if (unp->unp_conn)
562                 unp_disconnect(unp);
563         while (!LIST_EMPTY(&unp->unp_refs))
564                 unp_drop(LIST_FIRST(&unp->unp_refs), ECONNRESET);
565         soisdisconnected(unp->unp_socket);
566         unp->unp_socket->so_pcb = 0;
567         if (unp_rights) {
568                 /*
569                  * Normally the receive buffer is flushed later,
570                  * in sofree, but if our receive buffer holds references
571                  * to descriptors that are now garbage, we will dispose
572                  * of those descriptor references after the garbage collector
573                  * gets them (resulting in a "panic: closef: count < 0").
574                  */
575                 sorflush(unp->unp_socket);
576                 unp_gc();
577         }
578         if (unp->unp_addr)
579                 FREE(unp->unp_addr, M_SONAME);
580         zfree(unp_zone, unp);
581 }
582
583 static int
584 unp_bind(struct unpcb *unp, struct sockaddr *nam, struct thread *td)
585 {
586         struct proc *p = td->td_proc;
587         struct sockaddr_un *soun = (struct sockaddr_un *)nam;
588         struct vnode *vp;
589         struct vattr vattr;
590         int error, namelen;
591         struct nameidata nd;
592         char buf[SOCK_MAXADDRLEN];
593
594         if (unp->unp_vnode != NULL)
595                 return (EINVAL);
596         namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
597         if (namelen <= 0)
598                 return EINVAL;
599         strncpy(buf, soun->sun_path, namelen);
600         buf[namelen] = 0;       /* null-terminate the string */
601         NDINIT(&nd, NAMEI_CREATE, CNP_LOCKPARENT, UIO_SYSSPACE, buf, td);
602 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
603         error = namei(&nd);
604         if (error)
605                 return (error);
606         vp = nd.ni_vp;
607         if (vp != NULL) {
608                 NDFREE(&nd, NDF_ONLY_PNBUF);
609                 if (nd.ni_dvp == vp)
610                         vrele(nd.ni_dvp);
611                 else
612                         vput(nd.ni_dvp);
613                 vrele(vp);
614                 return (EADDRINUSE);
615         }
616         VATTR_NULL(&vattr);
617         vattr.va_type = VSOCK;
618         vattr.va_mode = (ACCESSPERMS & ~p->p_fd->fd_cmask);
619         VOP_LEASE(nd.ni_dvp, td, p->p_ucred, LEASE_WRITE);
620         error = VOP_CREATE(nd.ni_dvp, NCPNULL, &nd.ni_vp, &nd.ni_cnd, &vattr);
621         NDFREE(&nd, NDF_ONLY_PNBUF);
622         vput(nd.ni_dvp);
623         if (error)
624                 return (error);
625         vp = nd.ni_vp;
626         vp->v_socket = unp->unp_socket;
627         unp->unp_vnode = vp;
628         unp->unp_addr = (struct sockaddr_un *)dup_sockaddr(nam);
629         VOP_UNLOCK(vp, 0, td);
630         return (0);
631 }
632
633 static int
634 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
635 {
636         struct proc *p = td->td_proc;
637         struct sockaddr_un *soun = (struct sockaddr_un *)nam;
638         struct vnode *vp;
639         struct socket *so2, *so3;
640         struct unpcb *unp, *unp2, *unp3;
641         int error, len;
642         struct nameidata nd;
643         char buf[SOCK_MAXADDRLEN];
644
645         KKASSERT(p);
646
647         len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
648         if (len <= 0)
649                 return EINVAL;
650         strncpy(buf, soun->sun_path, len);
651         buf[len] = 0;
652
653         NDINIT(&nd, NAMEI_LOOKUP, CNP_FOLLOW | CNP_LOCKLEAF,
654             UIO_SYSSPACE, buf, td);
655         error = namei(&nd);
656         if (error)
657                 return (error);
658         vp = nd.ni_vp;
659         NDFREE(&nd, NDF_ONLY_PNBUF);
660         if (vp->v_type != VSOCK) {
661                 error = ENOTSOCK;
662                 goto bad;
663         }
664         error = VOP_ACCESS(vp, VWRITE, p->p_ucred, td);
665         if (error)
666                 goto bad;
667         so2 = vp->v_socket;
668         if (so2 == 0) {
669                 error = ECONNREFUSED;
670                 goto bad;
671         }
672         if (so->so_type != so2->so_type) {
673                 error = EPROTOTYPE;
674                 goto bad;
675         }
676         if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
677                 if ((so2->so_options & SO_ACCEPTCONN) == 0 ||
678                     (so3 = sonewconn(so2, 0)) == 0) {
679                         error = ECONNREFUSED;
680                         goto bad;
681                 }
682                 unp = sotounpcb(so);
683                 unp2 = sotounpcb(so2);
684                 unp3 = sotounpcb(so3);
685                 if (unp2->unp_addr)
686                         unp3->unp_addr = (struct sockaddr_un *)
687                                 dup_sockaddr((struct sockaddr *)unp2->unp_addr);
688
689                 /*
690                  * unp_peercred management:
691                  *
692                  * The connecter's (client's) credentials are copied
693                  * from its process structure at the time of connect()
694                  * (which is now).
695                  */
696                 cru2x(p->p_ucred, &unp3->unp_peercred);
697                 unp3->unp_flags |= UNP_HAVEPC;
698                 /*
699                  * The receiver's (server's) credentials are copied
700                  * from the unp_peercred member of socket on which the
701                  * former called listen(); unp_listen() cached that
702                  * process's credentials at that time so we can use
703                  * them now.
704                  */
705                 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
706                     ("unp_connect: listener without cached peercred"));
707                 memcpy(&unp->unp_peercred, &unp2->unp_peercred,
708                     sizeof(unp->unp_peercred));
709                 unp->unp_flags |= UNP_HAVEPC;
710
711                 so2 = so3;
712         }
713         error = unp_connect2(so, so2);
714 bad:
715         vput(vp);
716         return (error);
717 }
718
719 int
720 unp_connect2(so, so2)
721         struct socket *so;
722         struct socket *so2;
723 {
724         struct unpcb *unp = sotounpcb(so);
725         struct unpcb *unp2;
726
727         if (so2->so_type != so->so_type)
728                 return (EPROTOTYPE);
729         unp2 = sotounpcb(so2);
730         unp->unp_conn = unp2;
731         switch (so->so_type) {
732
733         case SOCK_DGRAM:
734                 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
735                 soisconnected(so);
736                 break;
737
738         case SOCK_STREAM:
739                 unp2->unp_conn = unp;
740                 soisconnected(so);
741                 soisconnected(so2);
742                 break;
743
744         default:
745                 panic("unp_connect2");
746         }
747         return (0);
748 }
749
750 static void
751 unp_disconnect(unp)
752         struct unpcb *unp;
753 {
754         struct unpcb *unp2 = unp->unp_conn;
755
756         if (unp2 == 0)
757                 return;
758         unp->unp_conn = 0;
759         switch (unp->unp_socket->so_type) {
760
761         case SOCK_DGRAM:
762                 LIST_REMOVE(unp, unp_reflink);
763                 unp->unp_socket->so_state &= ~SS_ISCONNECTED;
764                 break;
765
766         case SOCK_STREAM:
767                 soisdisconnected(unp->unp_socket);
768                 unp2->unp_conn = 0;
769                 soisdisconnected(unp2->unp_socket);
770                 break;
771         }
772 }
773
774 #ifdef notdef
775 void
776 unp_abort(unp)
777         struct unpcb *unp;
778 {
779
780         unp_detach(unp);
781 }
782 #endif
783
784 static int
785 prison_unpcb(struct thread *td, struct unpcb *unp)
786 {
787         struct proc *p;
788
789         if (td == NULL)
790                 return (0);
791         if ((p = td->td_proc) == NULL)
792                 return (0);
793         if (!p->p_ucred->cr_prison)
794                 return (0);
795         if (p->p_fd->fd_rdir == unp->unp_rvnode)
796                 return (0);
797         return (1);
798 }
799
800 static int
801 unp_pcblist(SYSCTL_HANDLER_ARGS)
802 {
803         int error, i, n;
804         struct unpcb *unp, **unp_list;
805         unp_gen_t gencnt;
806         struct xunpgen xug;
807         struct unp_head *head;
808
809         head = ((intptr_t)arg1 == SOCK_DGRAM ? &unp_dhead : &unp_shead);
810
811         KKASSERT(curproc != NULL);
812
813         /*
814          * The process of preparing the PCB list is too time-consuming and
815          * resource-intensive to repeat twice on every request.
816          */
817         if (req->oldptr == 0) {
818                 n = unp_count;
819                 req->oldidx = 2 * (sizeof xug)
820                         + (n + n/8) * sizeof(struct xunpcb);
821                 return 0;
822         }
823
824         if (req->newptr != 0)
825                 return EPERM;
826
827         /*
828          * OK, now we're committed to doing something.
829          */
830         gencnt = unp_gencnt;
831         n = unp_count;
832
833         xug.xug_len = sizeof xug;
834         xug.xug_count = n;
835         xug.xug_gen = gencnt;
836         xug.xug_sogen = so_gencnt;
837         error = SYSCTL_OUT(req, &xug, sizeof xug);
838         if (error)
839                 return error;
840
841         unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
842         if (unp_list == 0)
843                 return ENOMEM;
844         
845         for (unp = LIST_FIRST(head), i = 0; unp && i < n;
846              unp = LIST_NEXT(unp, unp_link)) {
847                 if (unp->unp_gencnt <= gencnt && !prison_unpcb(req->td, unp))
848                         unp_list[i++] = unp;
849         }
850         n = i;                  /* in case we lost some during malloc */
851
852         error = 0;
853         for (i = 0; i < n; i++) {
854                 unp = unp_list[i];
855                 if (unp->unp_gencnt <= gencnt) {
856                         struct xunpcb xu;
857                         xu.xu_len = sizeof xu;
858                         xu.xu_unpp = unp;
859                         /*
860                          * XXX - need more locking here to protect against
861                          * connect/disconnect races for SMP.
862                          */
863                         if (unp->unp_addr)
864                                 bcopy(unp->unp_addr, &xu.xu_addr, 
865                                       unp->unp_addr->sun_len);
866                         if (unp->unp_conn && unp->unp_conn->unp_addr)
867                                 bcopy(unp->unp_conn->unp_addr,
868                                       &xu.xu_caddr,
869                                       unp->unp_conn->unp_addr->sun_len);
870                         bcopy(unp, &xu.xu_unp, sizeof *unp);
871                         sotoxsocket(unp->unp_socket, &xu.xu_socket);
872                         error = SYSCTL_OUT(req, &xu, sizeof xu);
873                 }
874         }
875         if (!error) {
876                 /*
877                  * Give the user an updated idea of our state.
878                  * If the generation differs from what we told
879                  * her before, she knows that something happened
880                  * while we were processing this request, and it
881                  * might be necessary to retry.
882                  */
883                 xug.xug_gen = unp_gencnt;
884                 xug.xug_sogen = so_gencnt;
885                 xug.xug_count = unp_count;
886                 error = SYSCTL_OUT(req, &xug, sizeof xug);
887         }
888         free(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
899 static void
900 unp_shutdown(unp)
901         struct unpcb *unp;
902 {
903         struct socket *so;
904
905         if (unp->unp_socket->so_type == SOCK_STREAM && unp->unp_conn &&
906             (so = unp->unp_conn->unp_socket))
907                 socantrcvmore(so);
908 }
909
910 static void
911 unp_drop(unp, errno)
912         struct unpcb *unp;
913         int errno;
914 {
915         struct socket *so = unp->unp_socket;
916
917         so->so_error = errno;
918         unp_disconnect(unp);
919 }
920
921 #ifdef notdef
922 void
923 unp_drain()
924 {
925
926 }
927 #endif
928
929 int
930 unp_externalize(struct mbuf *rights)
931 {
932         struct proc *p = curproc;               /* XXX */
933         int i;
934         struct cmsghdr *cm = mtod(rights, struct cmsghdr *);
935         int *fdp;
936         struct file **rp;
937         struct file *fp;
938         int newfds = (cm->cmsg_len - (CMSG_DATA(cm) - (u_char *)cm))
939                 / sizeof (struct file *);
940         int f;
941
942         /*
943          * if the new FD's will not fit, then we free them all
944          */
945         if (!fdavail(p, newfds)) {
946                 rp = (struct file **)CMSG_DATA(cm);
947                 for (i = 0; i < newfds; i++) {
948                         fp = *rp;
949                         /*
950                          * zero the pointer before calling unp_discard,
951                          * since it may end up in unp_gc()..
952                          */
953                         *rp++ = 0;
954                         unp_discard(fp);
955                 }
956                 return (EMSGSIZE);
957         }
958         /*
959          * now change each pointer to an fd in the global table to 
960          * an integer that is the index to the local fd table entry
961          * that we set up to point to the global one we are transferring.
962          * If sizeof (struct file *) is bigger than or equal to sizeof int,
963          * then do it in forward order. In that case, an integer will
964          * always come in the same place or before its corresponding
965          * struct file pointer.
966          * If sizeof (struct file *) is smaller than sizeof int, then
967          * do it in reverse order.
968          */
969         if (sizeof (struct file *) >= sizeof (int)) {
970                 fdp = (int *)(cm + 1);
971                 rp = (struct file **)CMSG_DATA(cm);
972                 for (i = 0; i < newfds; i++) {
973                         if (fdalloc(p, 0, &f))
974                                 panic("unp_externalize");
975                         fp = *rp++;
976                         p->p_fd->fd_ofiles[f] = fp;
977                         fp->f_msgcount--;
978                         unp_rights--;
979                         *fdp++ = f;
980                 }
981         } else {
982                 fdp = (int *)(cm + 1) + newfds - 1;
983                 rp = (struct file **)CMSG_DATA(cm) + newfds - 1;
984                 for (i = 0; i < newfds; i++) {
985                         if (fdalloc(p, 0, &f))
986                                 panic("unp_externalize");
987                         fp = *rp--;
988                         p->p_fd->fd_ofiles[f] = fp;
989                         fp->f_msgcount--;
990                         unp_rights--;
991                         *fdp-- = f;
992                 }
993         }
994
995         /*
996          * Adjust length, in case sizeof(struct file *) and sizeof(int)
997          * differs.
998          */
999         cm->cmsg_len = CMSG_LEN(newfds * sizeof(int));
1000         rights->m_len = cm->cmsg_len;
1001         return (0);
1002 }
1003
1004 void
1005 unp_init(void)
1006 {
1007         unp_zone = zinit("unpcb", sizeof(struct unpcb), nmbclusters, 0, 0);
1008         if (unp_zone == 0)
1009                 panic("unp_init");
1010         LIST_INIT(&unp_dhead);
1011         LIST_INIT(&unp_shead);
1012 }
1013
1014 static int
1015 unp_internalize(struct mbuf *control, struct thread *td)
1016 {
1017         struct proc *p = td->td_proc;
1018         struct filedesc *fdescp;
1019         struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1020         struct file **rp;
1021         struct file *fp;
1022         int i, fd, *fdp;
1023         struct cmsgcred *cmcred;
1024         int oldfds;
1025         u_int newlen;
1026
1027         KKASSERT(p);
1028         fdescp = p->p_fd;
1029         if ((cm->cmsg_type != SCM_RIGHTS && cm->cmsg_type != SCM_CREDS) ||
1030             cm->cmsg_level != SOL_SOCKET || cm->cmsg_len != control->m_len)
1031                 return (EINVAL);
1032
1033         /*
1034          * Fill in credential information.
1035          */
1036         if (cm->cmsg_type == SCM_CREDS) {
1037                 cmcred = (struct cmsgcred *)(cm + 1);
1038                 cmcred->cmcred_pid = p->p_pid;
1039                 cmcred->cmcred_uid = p->p_ucred->cr_ruid;
1040                 cmcred->cmcred_gid = p->p_ucred->cr_rgid;
1041                 cmcred->cmcred_euid = p->p_ucred->cr_uid;
1042                 cmcred->cmcred_ngroups = MIN(p->p_ucred->cr_ngroups,
1043                                                         CMGROUP_MAX);
1044                 for (i = 0; i < cmcred->cmcred_ngroups; i++)
1045                         cmcred->cmcred_groups[i] = p->p_ucred->cr_groups[i];
1046                 return(0);
1047         }
1048
1049         oldfds = (cm->cmsg_len - sizeof (*cm)) / sizeof (int);
1050         /*
1051          * check that all the FDs passed in refer to legal OPEN files
1052          * If not, reject the entire operation.
1053          */
1054         fdp = (int *)(cm + 1);
1055         for (i = 0; i < oldfds; i++) {
1056                 fd = *fdp++;
1057                 if ((unsigned)fd >= fdescp->fd_nfiles ||
1058                     fdescp->fd_ofiles[fd] == NULL)
1059                         return (EBADF);
1060                 if (fdescp->fd_ofiles[fd]->f_type == DTYPE_KQUEUE)
1061                         return (EOPNOTSUPP);
1062         }
1063         /*
1064          * Now replace the integer FDs with pointers to
1065          * the associated global file table entry..
1066          * Allocate a bigger buffer as necessary. But if an cluster is not
1067          * enough, return E2BIG.
1068          */
1069         newlen = CMSG_LEN(oldfds * sizeof(struct file *));
1070         if (newlen > MCLBYTES)
1071                 return (E2BIG);
1072         if (newlen - control->m_len > M_TRAILINGSPACE(control)) {
1073                 if (control->m_flags & M_EXT)
1074                         return (E2BIG);
1075                 MCLGET(control, MB_WAIT);
1076                 if ((control->m_flags & M_EXT) == 0)
1077                         return (ENOBUFS);
1078
1079                 /* copy the data to the cluster */
1080                 memcpy(mtod(control, char *), cm, cm->cmsg_len);
1081                 cm = mtod(control, struct cmsghdr *);
1082         }
1083
1084         /*
1085          * Adjust length, in case sizeof(struct file *) and sizeof(int)
1086          * differs.
1087          */
1088         control->m_len = cm->cmsg_len = newlen;
1089
1090         /*
1091          * Transform the file descriptors into struct file pointers.
1092          * If sizeof (struct file *) is bigger than or equal to sizeof int,
1093          * then do it in reverse order so that the int won't get until
1094          * we're done.
1095          * If sizeof (struct file *) is smaller than sizeof int, then
1096          * do it in forward order.
1097          */
1098         if (sizeof (struct file *) >= sizeof (int)) {
1099                 fdp = (int *)(cm + 1) + oldfds - 1;
1100                 rp = (struct file **)CMSG_DATA(cm) + oldfds - 1;
1101                 for (i = 0; i < oldfds; i++) {
1102                         fp = fdescp->fd_ofiles[*fdp--];
1103                         *rp-- = fp;
1104                         fp->f_count++;
1105                         fp->f_msgcount++;
1106                         unp_rights++;
1107                 }
1108         } else {
1109                 fdp = (int *)(cm + 1);
1110                 rp = (struct file **)CMSG_DATA(cm);
1111                 for (i = 0; i < oldfds; i++) {
1112                         fp = fdescp->fd_ofiles[*fdp++];
1113                         *rp++ = fp;
1114                         fp->f_count++;
1115                         fp->f_msgcount++;
1116                         unp_rights++;
1117                 }
1118         }
1119         return (0);
1120 }
1121
1122 static int      unp_defer, unp_gcing;
1123
1124 static void
1125 unp_gc()
1126 {
1127         struct file *fp, *nextfp;
1128         struct socket *so;
1129         struct file **extra_ref, **fpp;
1130         int nunref, i;
1131
1132         if (unp_gcing)
1133                 return;
1134         unp_gcing = 1;
1135         unp_defer = 0;
1136         /* 
1137          * before going through all this, set all FDs to 
1138          * be NOT defered and NOT externally accessible
1139          */
1140         LIST_FOREACH(fp, &filehead, f_list)
1141                 fp->f_flag &= ~(FMARK|FDEFER);
1142         do {
1143                 LIST_FOREACH(fp, &filehead, f_list) {
1144                         /*
1145                          * If the file is not open, skip it
1146                          */
1147                         if (fp->f_count == 0)
1148                                 continue;
1149                         /*
1150                          * If we already marked it as 'defer'  in a
1151                          * previous pass, then try process it this time
1152                          * and un-mark it
1153                          */
1154                         if (fp->f_flag & FDEFER) {
1155                                 fp->f_flag &= ~FDEFER;
1156                                 unp_defer--;
1157                         } else {
1158                                 /*
1159                                  * if it's not defered, then check if it's
1160                                  * already marked.. if so skip it
1161                                  */
1162                                 if (fp->f_flag & FMARK)
1163                                         continue;
1164                                 /* 
1165                                  * If all references are from messages
1166                                  * in transit, then skip it. it's not 
1167                                  * externally accessible.
1168                                  */ 
1169                                 if (fp->f_count == fp->f_msgcount)
1170                                         continue;
1171                                 /* 
1172                                  * If it got this far then it must be
1173                                  * externally accessible.
1174                                  */
1175                                 fp->f_flag |= FMARK;
1176                         }
1177                         /*
1178                          * either it was defered, or it is externally 
1179                          * accessible and not already marked so.
1180                          * Now check if it is possibly one of OUR sockets.
1181                          */ 
1182                         if (fp->f_type != DTYPE_SOCKET ||
1183                             (so = (struct socket *)fp->f_data) == 0)
1184                                 continue;
1185                         if (so->so_proto->pr_domain != &localdomain ||
1186                             (so->so_proto->pr_flags&PR_RIGHTS) == 0)
1187                                 continue;
1188 #ifdef notdef
1189                         if (so->so_rcv.sb_flags & SB_LOCK) {
1190                                 /*
1191                                  * This is problematical; it's not clear
1192                                  * we need to wait for the sockbuf to be
1193                                  * unlocked (on a uniprocessor, at least),
1194                                  * and it's also not clear what to do
1195                                  * if sbwait returns an error due to receipt
1196                                  * of a signal.  If sbwait does return
1197                                  * an error, we'll go into an infinite
1198                                  * loop.  Delete all of this for now.
1199                                  */
1200                                 (void) sbwait(&so->so_rcv);
1201                                 goto restart;
1202                         }
1203 #endif
1204                         /*
1205                          * So, Ok, it's one of our sockets and it IS externally
1206                          * accessible (or was defered). Now we look
1207                          * to see if we hold any file descriptors in its
1208                          * message buffers. Follow those links and mark them 
1209                          * as accessible too.
1210                          */
1211                         unp_scan(so->so_rcv.sb_mb, unp_mark);
1212                 }
1213         } while (unp_defer);
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         extra_ref = malloc(nfiles * sizeof(struct file *), M_FILE, M_WAITOK);
1254         for (nunref = 0, fp = LIST_FIRST(&filehead), fpp = extra_ref; fp != 0;
1255             fp = nextfp) {
1256                 nextfp = LIST_NEXT(fp, f_list);
1257                 /* 
1258                  * If it's not open, skip it
1259                  */
1260                 if (fp->f_count == 0)
1261                         continue;
1262                 /* 
1263                  * If all refs are from msgs, and it's not marked accessible
1264                  * then it must be referenced from some unreachable cycle
1265                  * of (shut-down) FDs, so include it in our
1266                  * list of FDs to remove
1267                  */
1268                 if (fp->f_count == fp->f_msgcount && !(fp->f_flag & FMARK)) {
1269                         *fpp++ = fp;
1270                         nunref++;
1271                         fp->f_count++;
1272                 }
1273         }
1274         /* 
1275          * for each FD on our hit list, do the following two things
1276          */
1277         for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
1278                 struct file *tfp = *fpp;
1279                 if (tfp->f_type == DTYPE_SOCKET && tfp->f_data != NULL)
1280                         sorflush((struct socket *)(tfp->f_data));
1281         }
1282         for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp)
1283                 closef(*fpp, NULL);
1284         free((caddr_t)extra_ref, M_FILE);
1285         unp_gcing = 0;
1286 }
1287
1288 void
1289 unp_dispose(struct mbuf *m)
1290 {
1291         if (m)
1292                 unp_scan(m, unp_discard);
1293 }
1294
1295 static int
1296 unp_listen(struct unpcb *unp, struct thread *td)
1297 {
1298         struct proc *p = td->td_proc;
1299
1300         KKASSERT(p);
1301         cru2x(p->p_ucred, &unp->unp_peercred);
1302         unp->unp_flags |= UNP_HAVEPCCACHED;
1303         return (0);
1304 }
1305
1306 static void
1307 unp_scan(m0, op)
1308         struct mbuf *m0;
1309         void (*op) (struct file *);
1310 {
1311         struct mbuf *m;
1312         struct file **rp;
1313         struct cmsghdr *cm;
1314         int i;
1315         int qfds;
1316
1317         while (m0) {
1318                 for (m = m0; m; m = m->m_next)
1319                         if (m->m_type == MT_CONTROL &&
1320                             m->m_len >= sizeof(*cm)) {
1321                                 cm = mtod(m, struct cmsghdr *);
1322                                 if (cm->cmsg_level != SOL_SOCKET ||
1323                                     cm->cmsg_type != SCM_RIGHTS)
1324                                         continue;
1325                                 qfds = (cm->cmsg_len -
1326                                         (CMSG_DATA(cm) - (u_char *)cm))
1327                                                 / sizeof (struct file *);
1328                                 rp = (struct file **)CMSG_DATA(cm);
1329                                 for (i = 0; i < qfds; i++)
1330                                         (*op)(*rp++);
1331                                 break;          /* XXX, but saves time */
1332                         }
1333                 m0 = m0->m_nextpkt;
1334         }
1335 }
1336
1337 static void
1338 unp_mark(fp)
1339         struct file *fp;
1340 {
1341
1342         if (fp->f_flag & FMARK)
1343                 return;
1344         unp_defer++;
1345         fp->f_flag |= (FMARK|FDEFER);
1346 }
1347
1348 static void
1349 unp_discard(fp)
1350         struct file *fp;
1351 {
1352
1353         fp->f_msgcount--;
1354         unp_rights--;
1355         (void) closef(fp, NULL);
1356 }