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