The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/netinet/tcp_subr.c

Version: -  FREEBSD  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-2  -  FREEBSD-11-1  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-4  -  FREEBSD-10-3  -  FREEBSD-10-2  -  FREEBSD-10-1  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-3  -  FREEBSD-9-2  -  FREEBSD-9-1  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-4  -  FREEBSD-8-3  -  FREEBSD-8-2  -  FREEBSD-8-1  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-4  -  FREEBSD-7-3  -  FREEBSD-7-2  -  FREEBSD-7-1  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-4  -  FREEBSD-6-3  -  FREEBSD-6-2  -  FREEBSD-6-1  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-5  -  FREEBSD-5-4  -  FREEBSD-5-3  -  FREEBSD-5-2  -  FREEBSD-5-1  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  linux-2.6  -  linux-2.4.22  -  MK83  -  MK84  -  PLAN9  -  DFBSD  -  NETBSD  -  NETBSD5  -  NETBSD4  -  NETBSD3  -  NETBSD20  -  OPENBSD  -  xnu-517  -  xnu-792  -  xnu-792.6.70  -  xnu-1228  -  xnu-1456.1.26  -  xnu-1699.24.8  -  xnu-2050.18.24  -  OPENSOLARIS  -  minix-3-1-1 
SearchContext: -  none  -  3  -  10 

    1 /*-
    2  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
    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  * 4. Neither the name of the University nor the names of its contributors
   14  *    may be used to endorse or promote products derived from this software
   15  *    without specific prior written permission.
   16  *
   17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
   18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   27  * SUCH DAMAGE.
   28  *
   29  *      @(#)tcp_subr.c  8.2 (Berkeley) 5/24/95
   30  * $FreeBSD: releng/5.4/sys/netinet/tcp_subr.c 145979 2005-05-07 03:58:25Z cperciva $
   31  */
   32 
   33 #include "opt_compat.h"
   34 #include "opt_inet.h"
   35 #include "opt_inet6.h"
   36 #include "opt_ipsec.h"
   37 #include "opt_mac.h"
   38 #include "opt_tcpdebug.h"
   39 #include "opt_tcp_sack.h"
   40 
   41 #include <sys/param.h>
   42 #include <sys/systm.h>
   43 #include <sys/callout.h>
   44 #include <sys/kernel.h>
   45 #include <sys/sysctl.h>
   46 #include <sys/mac.h>
   47 #include <sys/malloc.h>
   48 #include <sys/mbuf.h>
   49 #ifdef INET6
   50 #include <sys/domain.h>
   51 #endif
   52 #include <sys/proc.h>
   53 #include <sys/socket.h>
   54 #include <sys/socketvar.h>
   55 #include <sys/protosw.h>
   56 #include <sys/random.h>
   57 
   58 #include <vm/uma.h>
   59 
   60 #include <net/route.h>
   61 #include <net/if.h>
   62 
   63 #include <netinet/in.h>
   64 #include <netinet/in_systm.h>
   65 #include <netinet/ip.h>
   66 #ifdef INET6
   67 #include <netinet/ip6.h>
   68 #endif
   69 #include <netinet/in_pcb.h>
   70 #ifdef INET6
   71 #include <netinet6/in6_pcb.h>
   72 #endif
   73 #include <netinet/in_var.h>
   74 #include <netinet/ip_var.h>
   75 #ifdef INET6
   76 #include <netinet6/ip6_var.h>
   77 #include <netinet6/nd6.h>
   78 #endif
   79 #include <netinet/tcp.h>
   80 #include <netinet/tcp_fsm.h>
   81 #include <netinet/tcp_seq.h>
   82 #include <netinet/tcp_timer.h>
   83 #include <netinet/tcp_var.h>
   84 #ifdef INET6
   85 #include <netinet6/tcp6_var.h>
   86 #endif
   87 #include <netinet/tcpip.h>
   88 #ifdef TCPDEBUG
   89 #include <netinet/tcp_debug.h>
   90 #endif
   91 #include <netinet6/ip6protosw.h>
   92 
   93 #ifdef IPSEC
   94 #include <netinet6/ipsec.h>
   95 #ifdef INET6
   96 #include <netinet6/ipsec6.h>
   97 #endif
   98 #include <netkey/key.h>
   99 #endif /*IPSEC*/
  100 
  101 #ifdef FAST_IPSEC
  102 #include <netipsec/ipsec.h>
  103 #include <netipsec/xform.h>
  104 #ifdef INET6
  105 #include <netipsec/ipsec6.h>
  106 #endif
  107 #include <netipsec/key.h>
  108 #define IPSEC
  109 #endif /*FAST_IPSEC*/
  110 
  111 #include <machine/in_cksum.h>
  112 #include <sys/md5.h>
  113 
  114 int     tcp_mssdflt = TCP_MSS;
  115 SYSCTL_INT(_net_inet_tcp, TCPCTL_MSSDFLT, mssdflt, CTLFLAG_RW,
  116     &tcp_mssdflt , 0, "Default TCP Maximum Segment Size");
  117 
  118 #ifdef INET6
  119 int     tcp_v6mssdflt = TCP6_MSS;
  120 SYSCTL_INT(_net_inet_tcp, TCPCTL_V6MSSDFLT, v6mssdflt,
  121         CTLFLAG_RW, &tcp_v6mssdflt , 0,
  122         "Default TCP Maximum Segment Size for IPv6");
  123 #endif
  124 
  125 /*
  126  * Minimum MSS we accept and use. This prevents DoS attacks where
  127  * we are forced to a ridiculous low MSS like 20 and send hundreds
  128  * of packets instead of one. The effect scales with the available
  129  * bandwidth and quickly saturates the CPU and network interface
  130  * with packet generation and sending. Set to zero to disable MINMSS
  131  * checking. This setting prevents us from sending too small packets.
  132  */
  133 int     tcp_minmss = TCP_MINMSS;
  134 SYSCTL_INT(_net_inet_tcp, OID_AUTO, minmss, CTLFLAG_RW,
  135     &tcp_minmss , 0, "Minmum TCP Maximum Segment Size");
  136 /*
  137  * Number of TCP segments per second we accept from remote host
  138  * before we start to calculate average segment size. If average
  139  * segment size drops below the minimum TCP MSS we assume a DoS
  140  * attack and reset+drop the connection. Care has to be taken not to
  141  * set this value too small to not kill interactive type connections
  142  * (telnet, SSH) which send many small packets.
  143  */
  144 int     tcp_minmssoverload = TCP_MINMSSOVERLOAD;
  145 SYSCTL_INT(_net_inet_tcp, OID_AUTO, minmssoverload, CTLFLAG_RW,
  146     &tcp_minmssoverload , 0, "Number of TCP Segments per Second allowed to"
  147     "be under the MINMSS Size");
  148 
  149 #if 0
  150 static int      tcp_rttdflt = TCPTV_SRTTDFLT / PR_SLOWHZ;
  151 SYSCTL_INT(_net_inet_tcp, TCPCTL_RTTDFLT, rttdflt, CTLFLAG_RW,
  152     &tcp_rttdflt , 0, "Default maximum TCP Round Trip Time");
  153 #endif
  154 
  155 int     tcp_do_rfc1323 = 1;
  156 SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1323, rfc1323, CTLFLAG_RW,
  157     &tcp_do_rfc1323 , 0, "Enable rfc1323 (high performance TCP) extensions");
  158 
  159 int     tcp_do_rfc1644 = 0;
  160 SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1644, rfc1644, CTLFLAG_RW,
  161     &tcp_do_rfc1644 , 0, "Enable rfc1644 (TTCP) extensions");
  162 
  163 static int      tcp_tcbhashsize = 0;
  164 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcbhashsize, CTLFLAG_RDTUN,
  165      &tcp_tcbhashsize, 0, "Size of TCP control-block hashtable");
  166 
  167 static int      do_tcpdrain = 1;
  168 SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_tcpdrain, CTLFLAG_RW, &do_tcpdrain, 0,
  169      "Enable tcp_drain routine for extra help when low on mbufs");
  170 
  171 SYSCTL_INT(_net_inet_tcp, OID_AUTO, pcbcount, CTLFLAG_RD,
  172     &tcbinfo.ipi_count, 0, "Number of active PCBs");
  173 
  174 static int      icmp_may_rst = 1;
  175 SYSCTL_INT(_net_inet_tcp, OID_AUTO, icmp_may_rst, CTLFLAG_RW, &icmp_may_rst, 0,
  176     "Certain ICMP unreachable messages may abort connections in SYN_SENT");
  177 
  178 static int      tcp_isn_reseed_interval = 0;
  179 SYSCTL_INT(_net_inet_tcp, OID_AUTO, isn_reseed_interval, CTLFLAG_RW,
  180     &tcp_isn_reseed_interval, 0, "Seconds between reseeding of ISN secret");
  181 
  182 /*
  183  * TCP bandwidth limiting sysctls.  Note that the default lower bound of
  184  * 1024 exists only for debugging.  A good production default would be
  185  * something like 6100.
  186  */
  187 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, inflight, CTLFLAG_RW, 0,
  188     "TCP inflight data limiting");
  189 
  190 static int      tcp_inflight_enable = 1;
  191 SYSCTL_INT(_net_inet_tcp_inflight, OID_AUTO, enable, CTLFLAG_RW,
  192     &tcp_inflight_enable, 0, "Enable automatic TCP inflight data limiting");
  193 
  194 static int      tcp_inflight_debug = 0;
  195 SYSCTL_INT(_net_inet_tcp_inflight, OID_AUTO, debug, CTLFLAG_RW,
  196     &tcp_inflight_debug, 0, "Debug TCP inflight calculations");
  197 
  198 static int      tcp_inflight_min = 6144;
  199 SYSCTL_INT(_net_inet_tcp_inflight, OID_AUTO, min, CTLFLAG_RW,
  200     &tcp_inflight_min, 0, "Lower-bound for TCP inflight window");
  201 
  202 static int      tcp_inflight_max = TCP_MAXWIN << TCP_MAX_WINSHIFT;
  203 SYSCTL_INT(_net_inet_tcp_inflight, OID_AUTO, max, CTLFLAG_RW,
  204     &tcp_inflight_max, 0, "Upper-bound for TCP inflight window");
  205 
  206 static int      tcp_inflight_stab = 20;
  207 SYSCTL_INT(_net_inet_tcp_inflight, OID_AUTO, stab, CTLFLAG_RW,
  208     &tcp_inflight_stab, 0, "Inflight Algorithm Stabilization 20 = 2 packets");
  209 
  210 uma_zone_t sack_hole_zone;
  211 
  212 static struct inpcb *tcp_notify(struct inpcb *, int);
  213 static void     tcp_discardcb(struct tcpcb *);
  214 static void     tcp_isn_tick(void *);
  215 
  216 /*
  217  * Target size of TCP PCB hash tables. Must be a power of two.
  218  *
  219  * Note that this can be overridden by the kernel environment
  220  * variable net.inet.tcp.tcbhashsize
  221  */
  222 #ifndef TCBHASHSIZE
  223 #define TCBHASHSIZE     512
  224 #endif
  225 
  226 /*
  227  * XXX
  228  * Callouts should be moved into struct tcp directly.  They are currently
  229  * separate because the tcpcb structure is exported to userland for sysctl
  230  * parsing purposes, which do not know about callouts.
  231  */
  232 struct  tcpcb_mem {
  233         struct  tcpcb tcb;
  234         struct  callout tcpcb_mem_rexmt, tcpcb_mem_persist, tcpcb_mem_keep;
  235         struct  callout tcpcb_mem_2msl, tcpcb_mem_delack;
  236 };
  237 
  238 static uma_zone_t tcpcb_zone;
  239 static uma_zone_t tcptw_zone;
  240 struct callout isn_callout;
  241 
  242 /*
  243  * Tcp initialization
  244  */
  245 void
  246 tcp_init()
  247 {
  248         int hashsize = TCBHASHSIZE;
  249 
  250         tcp_ccgen = 1;
  251 
  252         tcp_delacktime = TCPTV_DELACK;
  253         tcp_keepinit = TCPTV_KEEP_INIT;
  254         tcp_keepidle = TCPTV_KEEP_IDLE;
  255         tcp_keepintvl = TCPTV_KEEPINTVL;
  256         tcp_maxpersistidle = TCPTV_KEEP_IDLE;
  257         tcp_msl = TCPTV_MSL;
  258         tcp_rexmit_min = TCPTV_MIN;
  259         tcp_rexmit_slop = TCPTV_CPU_VAR;
  260 
  261         INP_INFO_LOCK_INIT(&tcbinfo, "tcp");
  262         LIST_INIT(&tcb);
  263         tcbinfo.listhead = &tcb;
  264         TUNABLE_INT_FETCH("net.inet.tcp.tcbhashsize", &hashsize);
  265         if (!powerof2(hashsize)) {
  266                 printf("WARNING: TCB hash size not a power of 2\n");
  267                 hashsize = 512; /* safe default */
  268         }
  269         tcp_tcbhashsize = hashsize;
  270         tcbinfo.hashbase = hashinit(hashsize, M_PCB, &tcbinfo.hashmask);
  271         tcbinfo.porthashbase = hashinit(hashsize, M_PCB,
  272                                         &tcbinfo.porthashmask);
  273         tcbinfo.ipi_zone = uma_zcreate("inpcb", sizeof(struct inpcb),
  274             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
  275         uma_zone_set_max(tcbinfo.ipi_zone, maxsockets);
  276 #ifdef INET6
  277 #define TCP_MINPROTOHDR (sizeof(struct ip6_hdr) + sizeof(struct tcphdr))
  278 #else /* INET6 */
  279 #define TCP_MINPROTOHDR (sizeof(struct tcpiphdr))
  280 #endif /* INET6 */
  281         if (max_protohdr < TCP_MINPROTOHDR)
  282                 max_protohdr = TCP_MINPROTOHDR;
  283         if (max_linkhdr + TCP_MINPROTOHDR > MHLEN)
  284                 panic("tcp_init");
  285 #undef TCP_MINPROTOHDR
  286         /*
  287          * These have to be type stable for the benefit of the timers.
  288          */
  289         tcpcb_zone = uma_zcreate("tcpcb", sizeof(struct tcpcb_mem),
  290             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
  291         uma_zone_set_max(tcpcb_zone, maxsockets);
  292         tcptw_zone = uma_zcreate("tcptw", sizeof(struct tcptw),
  293             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
  294         uma_zone_set_max(tcptw_zone, maxsockets / 5);
  295         tcp_timer_init();
  296         syncache_init();
  297         tcp_hc_init();
  298         tcp_reass_init();
  299         callout_init(&isn_callout, CALLOUT_MPSAFE);
  300         tcp_isn_tick(NULL);
  301         EVENTHANDLER_REGISTER(shutdown_pre_sync, tcp_fini, NULL,
  302                 SHUTDOWN_PRI_DEFAULT);
  303         sack_hole_zone = uma_zcreate("sackhole", sizeof(struct sackhole),
  304             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
  305 }
  306 
  307 void
  308 tcp_fini(xtp)
  309         void *xtp;
  310 {
  311         callout_stop(&isn_callout);
  312 
  313 }
  314 
  315 /*
  316  * Fill in the IP and TCP headers for an outgoing packet, given the tcpcb.
  317  * tcp_template used to store this data in mbufs, but we now recopy it out
  318  * of the tcpcb each time to conserve mbufs.
  319  */
  320 void
  321 tcpip_fillheaders(inp, ip_ptr, tcp_ptr)
  322         struct inpcb *inp;
  323         void *ip_ptr;
  324         void *tcp_ptr;
  325 {
  326         struct tcphdr *th = (struct tcphdr *)tcp_ptr;
  327 
  328         INP_LOCK_ASSERT(inp);
  329 
  330 #ifdef INET6
  331         if ((inp->inp_vflag & INP_IPV6) != 0) {
  332                 struct ip6_hdr *ip6;
  333 
  334                 ip6 = (struct ip6_hdr *)ip_ptr;
  335                 ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) |
  336                         (inp->in6p_flowinfo & IPV6_FLOWINFO_MASK);
  337                 ip6->ip6_vfc = (ip6->ip6_vfc & ~IPV6_VERSION_MASK) |
  338                         (IPV6_VERSION & IPV6_VERSION_MASK);
  339                 ip6->ip6_nxt = IPPROTO_TCP;
  340                 ip6->ip6_plen = sizeof(struct tcphdr);
  341                 ip6->ip6_src = inp->in6p_laddr;
  342                 ip6->ip6_dst = inp->in6p_faddr;
  343         } else
  344 #endif
  345         {
  346                 struct ip *ip;
  347 
  348                 ip = (struct ip *)ip_ptr;
  349                 ip->ip_v = IPVERSION;
  350                 ip->ip_hl = 5;
  351                 ip->ip_tos = inp->inp_ip_tos;
  352                 ip->ip_len = 0;
  353                 ip->ip_id = 0;
  354                 ip->ip_off = 0;
  355                 ip->ip_ttl = inp->inp_ip_ttl;
  356                 ip->ip_sum = 0;
  357                 ip->ip_p = IPPROTO_TCP;
  358                 ip->ip_src = inp->inp_laddr;
  359                 ip->ip_dst = inp->inp_faddr;
  360         }
  361         th->th_sport = inp->inp_lport;
  362         th->th_dport = inp->inp_fport;
  363         th->th_seq = 0;
  364         th->th_ack = 0;
  365         th->th_x2 = 0;
  366         th->th_off = 5;
  367         th->th_flags = 0;
  368         th->th_win = 0;
  369         th->th_urp = 0;
  370         th->th_sum = 0;         /* in_pseudo() is called later for ipv4 */
  371 }
  372 
  373 /*
  374  * Create template to be used to send tcp packets on a connection.
  375  * Allocates an mbuf and fills in a skeletal tcp/ip header.  The only
  376  * use for this function is in keepalives, which use tcp_respond.
  377  */
  378 struct tcptemp *
  379 tcpip_maketemplate(inp)
  380         struct inpcb *inp;
  381 {
  382         struct mbuf *m;
  383         struct tcptemp *n;
  384 
  385         m = m_get(M_DONTWAIT, MT_HEADER);
  386         if (m == NULL)
  387                 return (0);
  388         m->m_len = sizeof(struct tcptemp);
  389         n = mtod(m, struct tcptemp *);
  390 
  391         tcpip_fillheaders(inp, (void *)&n->tt_ipgen, (void *)&n->tt_t);
  392         return (n);
  393 }
  394 
  395 /*
  396  * Send a single message to the TCP at address specified by
  397  * the given TCP/IP header.  If m == NULL, then we make a copy
  398  * of the tcpiphdr at ti and send directly to the addressed host.
  399  * This is used to force keep alive messages out using the TCP
  400  * template for a connection.  If flags are given then we send
  401  * a message back to the TCP which originated the * segment ti,
  402  * and discard the mbuf containing it and any other attached mbufs.
  403  *
  404  * In any case the ack and sequence number of the transmitted
  405  * segment are as specified by the parameters.
  406  *
  407  * NOTE: If m != NULL, then ti must point to *inside* the mbuf.
  408  */
  409 void
  410 tcp_respond(tp, ipgen, th, m, ack, seq, flags)
  411         struct tcpcb *tp;
  412         void *ipgen;
  413         register struct tcphdr *th;
  414         register struct mbuf *m;
  415         tcp_seq ack, seq;
  416         int flags;
  417 {
  418         register int tlen;
  419         int win = 0;
  420         struct ip *ip;
  421         struct tcphdr *nth;
  422 #ifdef INET6
  423         struct ip6_hdr *ip6;
  424         int isipv6;
  425 #endif /* INET6 */
  426         int ipflags = 0;
  427         struct inpcb *inp;
  428 
  429         KASSERT(tp != NULL || m != NULL, ("tcp_respond: tp and m both NULL"));
  430 
  431 #ifdef INET6
  432         isipv6 = ((struct ip *)ipgen)->ip_v == 6;
  433         ip6 = ipgen;
  434 #endif /* INET6 */
  435         ip = ipgen;
  436 
  437         if (tp != NULL) {
  438                 inp = tp->t_inpcb;
  439                 KASSERT(inp != NULL, ("tcp control block w/o inpcb"));
  440                 INP_INFO_WLOCK_ASSERT(&tcbinfo);
  441                 INP_LOCK_ASSERT(inp);
  442         } else
  443                 inp = NULL;
  444 
  445         if (tp != NULL) {
  446                 if (!(flags & TH_RST)) {
  447                         win = sbspace(&inp->inp_socket->so_rcv);
  448                         if (win > (long)TCP_MAXWIN << tp->rcv_scale)
  449                                 win = (long)TCP_MAXWIN << tp->rcv_scale;
  450                 }
  451         }
  452         if (m == NULL) {
  453                 m = m_gethdr(M_DONTWAIT, MT_HEADER);
  454                 if (m == NULL)
  455                         return;
  456                 tlen = 0;
  457                 m->m_data += max_linkhdr;
  458 #ifdef INET6
  459                 if (isipv6) {
  460                         bcopy((caddr_t)ip6, mtod(m, caddr_t),
  461                               sizeof(struct ip6_hdr));
  462                         ip6 = mtod(m, struct ip6_hdr *);
  463                         nth = (struct tcphdr *)(ip6 + 1);
  464                 } else
  465 #endif /* INET6 */
  466               {
  467                 bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
  468                 ip = mtod(m, struct ip *);
  469                 nth = (struct tcphdr *)(ip + 1);
  470               }
  471                 bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr));
  472                 flags = TH_ACK;
  473         } else {
  474                 m_freem(m->m_next);
  475                 m->m_next = NULL;
  476                 m->m_data = (caddr_t)ipgen;
  477                 /* m_len is set later */
  478                 tlen = 0;
  479 #define xchg(a,b,type) { type t; t=a; a=b; b=t; }
  480 #ifdef INET6
  481                 if (isipv6) {
  482                         xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
  483                         nth = (struct tcphdr *)(ip6 + 1);
  484                 } else
  485 #endif /* INET6 */
  486               {
  487                 xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, n_long);
  488                 nth = (struct tcphdr *)(ip + 1);
  489               }
  490                 if (th != nth) {
  491                         /*
  492                          * this is usually a case when an extension header
  493                          * exists between the IPv6 header and the
  494                          * TCP header.
  495                          */
  496                         nth->th_sport = th->th_sport;
  497                         nth->th_dport = th->th_dport;
  498                 }
  499                 xchg(nth->th_dport, nth->th_sport, n_short);
  500 #undef xchg
  501         }
  502 #ifdef INET6
  503         if (isipv6) {
  504                 ip6->ip6_flow = 0;
  505                 ip6->ip6_vfc = IPV6_VERSION;
  506                 ip6->ip6_nxt = IPPROTO_TCP;
  507                 ip6->ip6_plen = htons((u_short)(sizeof (struct tcphdr) +
  508                                                 tlen));
  509                 tlen += sizeof (struct ip6_hdr) + sizeof (struct tcphdr);
  510         } else
  511 #endif
  512         {
  513                 tlen += sizeof (struct tcpiphdr);
  514                 ip->ip_len = tlen;
  515                 ip->ip_ttl = ip_defttl;
  516                 if (path_mtu_discovery)
  517                         ip->ip_off |= IP_DF;
  518         }
  519         m->m_len = tlen;
  520         m->m_pkthdr.len = tlen;
  521         m->m_pkthdr.rcvif = NULL;
  522 #ifdef MAC
  523         if (inp != NULL) {
  524                 /*
  525                  * Packet is associated with a socket, so allow the
  526                  * label of the response to reflect the socket label.
  527                  */
  528                 INP_LOCK_ASSERT(inp);
  529                 mac_create_mbuf_from_inpcb(inp, m);
  530         } else {
  531                 /*
  532                  * Packet is not associated with a socket, so possibly
  533                  * update the label in place.
  534                  */
  535                 mac_reflect_mbuf_tcp(m);
  536         }
  537 #endif
  538         nth->th_seq = htonl(seq);
  539         nth->th_ack = htonl(ack);
  540         nth->th_x2 = 0;
  541         nth->th_off = sizeof (struct tcphdr) >> 2;
  542         nth->th_flags = flags;
  543         if (tp != NULL)
  544                 nth->th_win = htons((u_short) (win >> tp->rcv_scale));
  545         else
  546                 nth->th_win = htons((u_short)win);
  547         nth->th_urp = 0;
  548 #ifdef INET6
  549         if (isipv6) {
  550                 nth->th_sum = 0;
  551                 nth->th_sum = in6_cksum(m, IPPROTO_TCP,
  552                                         sizeof(struct ip6_hdr),
  553                                         tlen - sizeof(struct ip6_hdr));
  554                 ip6->ip6_hlim = in6_selecthlim(tp != NULL ? tp->t_inpcb :
  555                     NULL, NULL);
  556         } else
  557 #endif /* INET6 */
  558         {
  559                 nth->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
  560                     htons((u_short)(tlen - sizeof(struct ip) + ip->ip_p)));
  561                 m->m_pkthdr.csum_flags = CSUM_TCP;
  562                 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
  563         }
  564 #ifdef TCPDEBUG
  565         if (tp == NULL || (inp->inp_socket->so_options & SO_DEBUG))
  566                 tcp_trace(TA_OUTPUT, 0, tp, mtod(m, void *), th, 0);
  567 #endif
  568 #ifdef INET6
  569         if (isipv6)
  570                 (void) ip6_output(m, NULL, NULL, ipflags, NULL, NULL, inp);
  571         else
  572 #endif /* INET6 */
  573         (void) ip_output(m, NULL, NULL, ipflags, NULL, inp);
  574 }
  575 
  576 /*
  577  * Create a new TCP control block, making an
  578  * empty reassembly queue and hooking it to the argument
  579  * protocol control block.  The `inp' parameter must have
  580  * come from the zone allocator set up in tcp_init().
  581  */
  582 struct tcpcb *
  583 tcp_newtcpcb(inp)
  584         struct inpcb *inp;
  585 {
  586         struct tcpcb_mem *tm;
  587         struct tcpcb *tp;
  588 #ifdef INET6
  589         int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
  590 #endif /* INET6 */
  591         int callout_flag;
  592 
  593         tm = uma_zalloc(tcpcb_zone, M_NOWAIT | M_ZERO);
  594         if (tm == NULL)
  595                 return (NULL);
  596         tp = &tm->tcb;
  597         /*      LIST_INIT(&tp->t_segq); */      /* XXX covered by M_ZERO */
  598         tp->t_maxseg = tp->t_maxopd =
  599 #ifdef INET6
  600                 isipv6 ? tcp_v6mssdflt :
  601 #endif /* INET6 */
  602                 tcp_mssdflt;
  603 
  604         /* Set up our timeouts. */
  605         callout_flag = debug_mpsafenet ? CALLOUT_MPSAFE : 0;
  606         callout_init(tp->tt_rexmt = &tm->tcpcb_mem_rexmt, callout_flag);
  607         callout_init(tp->tt_persist = &tm->tcpcb_mem_persist, callout_flag);
  608         callout_init(tp->tt_keep = &tm->tcpcb_mem_keep, callout_flag);
  609         callout_init(tp->tt_2msl = &tm->tcpcb_mem_2msl, callout_flag);
  610         callout_init(tp->tt_delack = &tm->tcpcb_mem_delack, callout_flag);
  611 
  612         if (tcp_do_rfc1323)
  613                 tp->t_flags = (TF_REQ_SCALE|TF_REQ_TSTMP);
  614         if (tcp_do_rfc1644)
  615                 tp->t_flags |= TF_REQ_CC;
  616         tp->sack_enable = tcp_do_sack;
  617         tp->t_inpcb = inp;      /* XXX */
  618         /*
  619          * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
  620          * rtt estimate.  Set rttvar so that srtt + 4 * rttvar gives
  621          * reasonable initial retransmit time.
  622          */
  623         tp->t_srtt = TCPTV_SRTTBASE;
  624         tp->t_rttvar = ((TCPTV_RTOBASE - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4;
  625         tp->t_rttmin = tcp_rexmit_min;
  626         tp->t_rxtcur = TCPTV_RTOBASE;
  627         tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
  628         tp->snd_bwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
  629         tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
  630         tp->t_rcvtime = ticks;
  631         tp->t_bw_rtttime = ticks;
  632         /*
  633          * IPv4 TTL initialization is necessary for an IPv6 socket as well,
  634          * because the socket may be bound to an IPv6 wildcard address,
  635          * which may match an IPv4-mapped IPv6 address.
  636          */
  637         inp->inp_ip_ttl = ip_defttl;
  638         inp->inp_ppcb = (caddr_t)tp;
  639         return (tp);            /* XXX */
  640 }
  641 
  642 /*
  643  * Drop a TCP connection, reporting
  644  * the specified error.  If connection is synchronized,
  645  * then send a RST to peer.
  646  */
  647 struct tcpcb *
  648 tcp_drop(tp, errno)
  649         register struct tcpcb *tp;
  650         int errno;
  651 {
  652         struct socket *so = tp->t_inpcb->inp_socket;
  653 
  654         INP_LOCK_ASSERT(tp->t_inpcb);
  655         if (TCPS_HAVERCVDSYN(tp->t_state)) {
  656                 tp->t_state = TCPS_CLOSED;
  657                 (void) tcp_output(tp);
  658                 tcpstat.tcps_drops++;
  659         } else
  660                 tcpstat.tcps_conndrops++;
  661         if (errno == ETIMEDOUT && tp->t_softerror)
  662                 errno = tp->t_softerror;
  663         so->so_error = errno;
  664         return (tcp_close(tp));
  665 }
  666 
  667 static void
  668 tcp_discardcb(tp)
  669         struct tcpcb *tp;
  670 {
  671         struct tseg_qent *q;
  672         struct inpcb *inp = tp->t_inpcb;
  673         struct socket *so = inp->inp_socket;
  674 #ifdef INET6
  675         int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
  676 #endif /* INET6 */
  677 
  678         INP_LOCK_ASSERT(inp);
  679 
  680         /*
  681          * Make sure that all of our timers are stopped before we
  682          * delete the PCB.
  683          */
  684         callout_stop(tp->tt_rexmt);
  685         callout_stop(tp->tt_persist);
  686         callout_stop(tp->tt_keep);
  687         callout_stop(tp->tt_2msl);
  688         callout_stop(tp->tt_delack);
  689 
  690         /*
  691          * If we got enough samples through the srtt filter,
  692          * save the rtt and rttvar in the routing entry.
  693          * 'Enough' is arbitrarily defined as 4 rtt samples.
  694          * 4 samples is enough for the srtt filter to converge
  695          * to within enough % of the correct value; fewer samples
  696          * and we could save a bogus rtt. The danger is not high
  697          * as tcp quickly recovers from everything.
  698          * XXX: Works very well but needs some more statistics!
  699          */
  700         if (tp->t_rttupdated >= 4) {
  701                 struct hc_metrics_lite metrics;
  702                 u_long ssthresh;
  703 
  704                 bzero(&metrics, sizeof(metrics));
  705                 /*
  706                  * Update the ssthresh always when the conditions below
  707                  * are satisfied. This gives us better new start value
  708                  * for the congestion avoidance for new connections.
  709                  * ssthresh is only set if packet loss occured on a session.
  710                  */
  711                 ssthresh = tp->snd_ssthresh;
  712                 if (ssthresh != 0 && ssthresh < so->so_snd.sb_hiwat / 2) {
  713                         /*
  714                          * convert the limit from user data bytes to
  715                          * packets then to packet data bytes.
  716                          */
  717                         ssthresh = (ssthresh + tp->t_maxseg / 2) / tp->t_maxseg;
  718                         if (ssthresh < 2)
  719                                 ssthresh = 2;
  720                         ssthresh *= (u_long)(tp->t_maxseg +
  721 #ifdef INET6
  722                                       (isipv6 ? sizeof (struct ip6_hdr) +
  723                                                sizeof (struct tcphdr) :
  724 #endif
  725                                        sizeof (struct tcpiphdr)
  726 #ifdef INET6
  727                                        )
  728 #endif
  729                                       );
  730                 } else
  731                         ssthresh = 0;
  732                 metrics.rmx_ssthresh = ssthresh;
  733 
  734                 metrics.rmx_rtt = tp->t_srtt;
  735                 metrics.rmx_rttvar = tp->t_rttvar;
  736                 /* XXX: This wraps if the pipe is more than 4 Gbit per second */
  737                 metrics.rmx_bandwidth = tp->snd_bandwidth;
  738                 metrics.rmx_cwnd = tp->snd_cwnd;
  739                 metrics.rmx_sendpipe = 0;
  740                 metrics.rmx_recvpipe = 0;
  741 
  742                 tcp_hc_update(&inp->inp_inc, &metrics);
  743         }
  744 
  745         /* free the reassembly queue, if any */
  746         while ((q = LIST_FIRST(&tp->t_segq)) != NULL) {
  747                 LIST_REMOVE(q, tqe_q);
  748                 m_freem(q->tqe_m);
  749                 uma_zfree(tcp_reass_zone, q);
  750                 tp->t_segqlen--;
  751                 tcp_reass_qsize--;
  752         }
  753         tcp_free_sackholes(tp);
  754         inp->inp_ppcb = NULL;
  755         tp->t_inpcb = NULL;
  756         uma_zfree(tcpcb_zone, tp);
  757         soisdisconnected(so);
  758 }
  759 
  760 /*
  761  * Close a TCP control block:
  762  *    discard all space held by the tcp
  763  *    discard internet protocol block
  764  *    wake up any sleepers
  765  */
  766 struct tcpcb *
  767 tcp_close(tp)
  768         struct tcpcb *tp;
  769 {
  770         struct inpcb *inp = tp->t_inpcb;
  771 #ifdef INET6
  772         struct socket *so = inp->inp_socket;
  773 #endif
  774 
  775         INP_LOCK_ASSERT(inp);
  776 
  777         tcp_discardcb(tp);
  778 #ifdef INET6
  779         if (INP_CHECK_SOCKAF(so, AF_INET6))
  780                 in6_pcbdetach(inp);
  781         else
  782 #endif
  783                 in_pcbdetach(inp);
  784         tcpstat.tcps_closed++;
  785         return (NULL);
  786 }
  787 
  788 void
  789 tcp_drain()
  790 {
  791         if (do_tcpdrain)
  792         {
  793                 struct inpcb *inpb;
  794                 struct tcpcb *tcpb;
  795                 struct tseg_qent *te;
  796 
  797         /*
  798          * Walk the tcpbs, if existing, and flush the reassembly queue,
  799          * if there is one...
  800          * XXX: The "Net/3" implementation doesn't imply that the TCP
  801          *      reassembly queue should be flushed, but in a situation
  802          *      where we're really low on mbufs, this is potentially
  803          *      usefull.
  804          */
  805                 INP_INFO_RLOCK(&tcbinfo);
  806                 LIST_FOREACH(inpb, tcbinfo.listhead, inp_list) {
  807                         if (inpb->inp_vflag & INP_TIMEWAIT)
  808                                 continue;
  809                         INP_LOCK(inpb);
  810                         if ((tcpb = intotcpcb(inpb)) != NULL) {
  811                                 while ((te = LIST_FIRST(&tcpb->t_segq))
  812                                     != NULL) {
  813                                         LIST_REMOVE(te, tqe_q);
  814                                         m_freem(te->tqe_m);
  815                                         uma_zfree(tcp_reass_zone, te);
  816                                         tcpb->t_segqlen--;
  817                                         tcp_reass_qsize--;
  818                                 }
  819                         }
  820                         INP_UNLOCK(inpb);
  821                 }
  822                 INP_INFO_RUNLOCK(&tcbinfo);
  823         }
  824 }
  825 
  826 /*
  827  * Notify a tcp user of an asynchronous error;
  828  * store error as soft error, but wake up user
  829  * (for now, won't do anything until can select for soft error).
  830  *
  831  * Do not wake up user since there currently is no mechanism for
  832  * reporting soft errors (yet - a kqueue filter may be added).
  833  */
  834 static struct inpcb *
  835 tcp_notify(inp, error)
  836         struct inpcb *inp;
  837         int error;
  838 {
  839         struct tcpcb *tp = (struct tcpcb *)inp->inp_ppcb;
  840 
  841         INP_LOCK_ASSERT(inp);
  842 
  843         /*
  844          * Ignore some errors if we are hooked up.
  845          * If connection hasn't completed, has retransmitted several times,
  846          * and receives a second error, give up now.  This is better
  847          * than waiting a long time to establish a connection that
  848          * can never complete.
  849          */
  850         if (tp->t_state == TCPS_ESTABLISHED &&
  851             (error == EHOSTUNREACH || error == ENETUNREACH ||
  852              error == EHOSTDOWN)) {
  853                 return (inp);
  854         } else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 &&
  855             tp->t_softerror) {
  856                 tcp_drop(tp, error);
  857                 return (struct inpcb *)0;
  858         } else {
  859                 tp->t_softerror = error;
  860                 return (inp);
  861         }
  862 #if 0
  863         wakeup( &so->so_timeo);
  864         sorwakeup(so);
  865         sowwakeup(so);
  866 #endif
  867 }
  868 
  869 static int
  870 tcp_pcblist(SYSCTL_HANDLER_ARGS)
  871 {
  872         int error, i, n, s;
  873         struct inpcb *inp, **inp_list;
  874         inp_gen_t gencnt;
  875         struct xinpgen xig;
  876 
  877         /*
  878          * The process of preparing the TCB list is too time-consuming and
  879          * resource-intensive to repeat twice on every request.
  880          */
  881         if (req->oldptr == NULL) {
  882                 n = tcbinfo.ipi_count;
  883                 req->oldidx = 2 * (sizeof xig)
  884                         + (n + n/8) * sizeof(struct xtcpcb);
  885                 return (0);
  886         }
  887 
  888         if (req->newptr != NULL)
  889                 return (EPERM);
  890 
  891         /*
  892          * OK, now we're committed to doing something.
  893          */
  894         s = splnet();
  895         INP_INFO_RLOCK(&tcbinfo);
  896         gencnt = tcbinfo.ipi_gencnt;
  897         n = tcbinfo.ipi_count;
  898         INP_INFO_RUNLOCK(&tcbinfo);
  899         splx(s);
  900 
  901         error = sysctl_wire_old_buffer(req, 2 * (sizeof xig)
  902                 + n * sizeof(struct xtcpcb));
  903         if (error != 0)
  904                 return (error);
  905 
  906         xig.xig_len = sizeof xig;
  907         xig.xig_count = n;
  908         xig.xig_gen = gencnt;
  909         xig.xig_sogen = so_gencnt;
  910         error = SYSCTL_OUT(req, &xig, sizeof xig);
  911         if (error)
  912                 return (error);
  913 
  914         inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK);
  915         if (inp_list == NULL)
  916                 return (ENOMEM);
  917 
  918         s = splnet();
  919         INP_INFO_RLOCK(&tcbinfo);
  920         for (inp = LIST_FIRST(tcbinfo.listhead), i = 0; inp != NULL && i < n;
  921              inp = LIST_NEXT(inp, inp_list)) {
  922                 INP_LOCK(inp);
  923                 if (inp->inp_gencnt <= gencnt) {
  924                         /*
  925                          * XXX: This use of cr_cansee(), introduced with
  926                          * TCP state changes, is not quite right, but for
  927                          * now, better than nothing.
  928                          */
  929                         if (inp->inp_vflag & INP_TIMEWAIT)
  930                                 error = cr_cansee(req->td->td_ucred,
  931                                     intotw(inp)->tw_cred);
  932                         else
  933                                 error = cr_canseesocket(req->td->td_ucred,
  934                                     inp->inp_socket);
  935                         if (error == 0)
  936                                 inp_list[i++] = inp;
  937                 }
  938                 INP_UNLOCK(inp);
  939         }
  940         INP_INFO_RUNLOCK(&tcbinfo);
  941         splx(s);
  942         n = i;
  943 
  944         error = 0;
  945         for (i = 0; i < n; i++) {
  946                 inp = inp_list[i];
  947                 if (inp->inp_gencnt <= gencnt) {
  948                         struct xtcpcb xt;
  949                         caddr_t inp_ppcb;
  950 
  951                         bzero(&xt, sizeof(xt));
  952                         xt.xt_len = sizeof xt;
  953                         /* XXX should avoid extra copy */
  954                         bcopy(inp, &xt.xt_inp, sizeof *inp);
  955                         inp_ppcb = inp->inp_ppcb;
  956                         if (inp_ppcb == NULL)
  957                                 bzero((char *) &xt.xt_tp, sizeof xt.xt_tp);
  958                         else if (inp->inp_vflag & INP_TIMEWAIT) {
  959                                 bzero((char *) &xt.xt_tp, sizeof xt.xt_tp);
  960                                 xt.xt_tp.t_state = TCPS_TIME_WAIT;
  961                         } else
  962                                 bcopy(inp_ppcb, &xt.xt_tp, sizeof xt.xt_tp);
  963                         if (inp->inp_socket != NULL)
  964                                 sotoxsocket(inp->inp_socket, &xt.xt_socket);
  965                         else {
  966                                 bzero(&xt.xt_socket, sizeof xt.xt_socket);
  967                                 xt.xt_socket.xso_protocol = IPPROTO_TCP;
  968                         }
  969                         xt.xt_inp.inp_gencnt = inp->inp_gencnt;
  970                         error = SYSCTL_OUT(req, &xt, sizeof xt);
  971                 }
  972         }
  973         if (!error) {
  974                 /*
  975                  * Give the user an updated idea of our state.
  976                  * If the generation differs from what we told
  977                  * her before, she knows that something happened
  978                  * while we were processing this request, and it
  979                  * might be necessary to retry.
  980                  */
  981                 s = splnet();
  982                 INP_INFO_RLOCK(&tcbinfo);
  983                 xig.xig_gen = tcbinfo.ipi_gencnt;
  984                 xig.xig_sogen = so_gencnt;
  985                 xig.xig_count = tcbinfo.ipi_count;
  986                 INP_INFO_RUNLOCK(&tcbinfo);
  987                 splx(s);
  988                 error = SYSCTL_OUT(req, &xig, sizeof xig);
  989         }
  990         free(inp_list, M_TEMP);
  991         return (error);
  992 }
  993 
  994 SYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist, CTLFLAG_RD, 0, 0,
  995             tcp_pcblist, "S,xtcpcb", "List of active TCP connections");
  996 
  997 static int
  998 tcp_getcred(SYSCTL_HANDLER_ARGS)
  999 {
 1000         struct xucred xuc;
 1001         struct sockaddr_in addrs[2];
 1002         struct inpcb *inp;
 1003         int error, s;
 1004 
 1005         error = suser_cred(req->td->td_ucred, SUSER_ALLOWJAIL);
 1006         if (error)
 1007                 return (error);
 1008         error = SYSCTL_IN(req, addrs, sizeof(addrs));
 1009         if (error)
 1010                 return (error);
 1011         s = splnet();
 1012         INP_INFO_RLOCK(&tcbinfo);
 1013         inp = in_pcblookup_hash(&tcbinfo, addrs[1].sin_addr, addrs[1].sin_port,
 1014             addrs[0].sin_addr, addrs[0].sin_port, 0, NULL);
 1015         if (inp == NULL) {
 1016                 error = ENOENT;
 1017                 goto outunlocked;
 1018         }
 1019         INP_LOCK(inp);
 1020         if (inp->inp_socket == NULL) {
 1021                 error = ENOENT;
 1022                 goto out;
 1023         }
 1024         error = cr_canseesocket(req->td->td_ucred, inp->inp_socket);
 1025         if (error)
 1026                 goto out;
 1027         cru2x(inp->inp_socket->so_cred, &xuc);
 1028 out:
 1029         INP_UNLOCK(inp);
 1030 outunlocked:
 1031         INP_INFO_RUNLOCK(&tcbinfo);
 1032         splx(s);
 1033         if (error == 0)
 1034                 error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
 1035         return (error);
 1036 }
 1037 
 1038 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, getcred,
 1039     CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0,
 1040     tcp_getcred, "S,xucred", "Get the xucred of a TCP connection");
 1041 
 1042 #ifdef INET6
 1043 static int
 1044 tcp6_getcred(SYSCTL_HANDLER_ARGS)
 1045 {
 1046         struct xucred xuc;
 1047         struct sockaddr_in6 addrs[2];
 1048         struct in6_addr a6[2];
 1049         struct inpcb *inp;
 1050         int error, s, mapped = 0;
 1051 
 1052         error = suser_cred(req->td->td_ucred, SUSER_ALLOWJAIL);
 1053         if (error)
 1054                 return (error);
 1055         error = SYSCTL_IN(req, addrs, sizeof(addrs));
 1056         if (error)
 1057                 return (error);
 1058         if (IN6_IS_ADDR_V4MAPPED(&addrs[0].sin6_addr)) {
 1059                 if (IN6_IS_ADDR_V4MAPPED(&addrs[1].sin6_addr))
 1060                         mapped = 1;
 1061                 else
 1062                         return (EINVAL);
 1063         } else {
 1064                 error = in6_embedscope(&a6[0], &addrs[0], NULL, NULL);
 1065                 if (error)
 1066                         return (EINVAL);
 1067                 error = in6_embedscope(&a6[1], &addrs[1], NULL, NULL);
 1068                 if (error)
 1069                         return (EINVAL);
 1070         }
 1071         s = splnet();
 1072         INP_INFO_RLOCK(&tcbinfo);
 1073         if (mapped == 1)
 1074                 inp = in_pcblookup_hash(&tcbinfo,
 1075                         *(struct in_addr *)&addrs[1].sin6_addr.s6_addr[12],
 1076                         addrs[1].sin6_port,
 1077                         *(struct in_addr *)&addrs[0].sin6_addr.s6_addr[12],
 1078                         addrs[0].sin6_port,
 1079                         0, NULL);
 1080         else
 1081                 inp = in6_pcblookup_hash(&tcbinfo, &a6[1], addrs[1].sin6_port,
 1082                         &a6[0], addrs[0].sin6_port, 0, NULL);
 1083         if (inp == NULL) {
 1084                 error = ENOENT;
 1085                 goto outunlocked;
 1086         }
 1087         INP_LOCK(inp);
 1088         if (inp->inp_socket == NULL) {
 1089                 error = ENOENT;
 1090                 goto out;
 1091         }
 1092         error = cr_canseesocket(req->td->td_ucred, inp->inp_socket);
 1093         if (error)
 1094                 goto out;
 1095         cru2x(inp->inp_socket->so_cred, &xuc);
 1096 out:
 1097         INP_UNLOCK(inp);
 1098 outunlocked:
 1099         INP_INFO_RUNLOCK(&tcbinfo);
 1100         splx(s);
 1101         if (error == 0)
 1102                 error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
 1103         return (error);
 1104 }
 1105 
 1106 SYSCTL_PROC(_net_inet6_tcp6, OID_AUTO, getcred,
 1107     CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0,
 1108     tcp6_getcred, "S,xucred", "Get the xucred of a TCP6 connection");
 1109 #endif
 1110 
 1111 
 1112 void
 1113 tcp_ctlinput(cmd, sa, vip)
 1114         int cmd;
 1115         struct sockaddr *sa;
 1116         void *vip;
 1117 {
 1118         struct ip *ip = vip;
 1119         struct tcphdr *th;
 1120         struct in_addr faddr;
 1121         struct inpcb *inp;
 1122         struct tcpcb *tp;
 1123         struct inpcb *(*notify)(struct inpcb *, int) = tcp_notify;
 1124         tcp_seq icmp_seq;
 1125         int s;
 1126 
 1127         faddr = ((struct sockaddr_in *)sa)->sin_addr;
 1128         if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
 1129                 return;
 1130 
 1131         if (cmd == PRC_QUENCH)
 1132                 notify = tcp_quench;
 1133         else if (icmp_may_rst && (cmd == PRC_UNREACH_ADMIN_PROHIB ||
 1134                 cmd == PRC_UNREACH_PORT || cmd == PRC_TIMXCEED_INTRANS) && ip)
 1135                 notify = tcp_drop_syn_sent;
 1136         else if (cmd == PRC_MSGSIZE)
 1137                 notify = tcp_mtudisc;
 1138         /*
 1139          * Redirects don't need to be handled up here.
 1140          */
 1141         else if (PRC_IS_REDIRECT(cmd))
 1142                 return;
 1143         /*
 1144          * Hostdead is ugly because it goes linearly through all PCBs.
 1145          * XXX: We never get this from ICMP, otherwise it makes an
 1146          * excellent DoS attack on machines with many connections.
 1147          */
 1148         else if (cmd == PRC_HOSTDEAD)
 1149                 ip = NULL;
 1150         else if ((unsigned)cmd >= PRC_NCMDS || inetctlerrmap[cmd] == 0)
 1151                 return;
 1152         if (ip != NULL) {
 1153                 s = splnet();
 1154                 th = (struct tcphdr *)((caddr_t)ip
 1155                                        + (ip->ip_hl << 2));
 1156                 INP_INFO_WLOCK(&tcbinfo);
 1157                 inp = in_pcblookup_hash(&tcbinfo, faddr, th->th_dport,
 1158                     ip->ip_src, th->th_sport, 0, NULL);
 1159                 if (inp != NULL)  {
 1160                         INP_LOCK(inp);
 1161                         if (inp->inp_socket != NULL) {
 1162                                 icmp_seq = htonl(th->th_seq);
 1163                                 tp = intotcpcb(inp);
 1164                                 if (SEQ_GEQ(icmp_seq, tp->snd_una) &&
 1165                                         SEQ_LT(icmp_seq, tp->snd_max))
 1166                                         inp = (*notify)(inp, inetctlerrmap[cmd]);
 1167                         }
 1168                         if (inp != NULL)
 1169                                 INP_UNLOCK(inp);
 1170                 } else {
 1171                         struct in_conninfo inc;
 1172 
 1173                         inc.inc_fport = th->th_dport;
 1174                         inc.inc_lport = th->th_sport;
 1175                         inc.inc_faddr = faddr;
 1176                         inc.inc_laddr = ip->ip_src;
 1177 #ifdef INET6
 1178                         inc.inc_isipv6 = 0;
 1179 #endif
 1180                         syncache_unreach(&inc, th);
 1181                 }
 1182                 INP_INFO_WUNLOCK(&tcbinfo);
 1183                 splx(s);
 1184         } else
 1185                 in_pcbnotifyall(&tcbinfo, faddr, inetctlerrmap[cmd], notify);
 1186 }
 1187 
 1188 #ifdef INET6
 1189 void
 1190 tcp6_ctlinput(cmd, sa, d)
 1191         int cmd;
 1192         struct sockaddr *sa;
 1193         void *d;
 1194 {
 1195         struct tcphdr th;
 1196         struct inpcb *(*notify)(struct inpcb *, int) = tcp_notify;
 1197         struct ip6_hdr *ip6;
 1198         struct mbuf *m;
 1199         struct ip6ctlparam *ip6cp = NULL;
 1200         const struct sockaddr_in6 *sa6_src = NULL;
 1201         int off;
 1202         struct tcp_portonly {
 1203                 u_int16_t th_sport;
 1204                 u_int16_t th_dport;
 1205         } *thp;
 1206 
 1207         if (sa->sa_family != AF_INET6 ||
 1208             sa->sa_len != sizeof(struct sockaddr_in6))
 1209                 return;
 1210 
 1211         if (cmd == PRC_QUENCH)
 1212                 notify = tcp_quench;
 1213         else if (cmd == PRC_MSGSIZE)
 1214                 notify = tcp_mtudisc;
 1215         else if (!PRC_IS_REDIRECT(cmd) &&
 1216                  ((unsigned)cmd >= PRC_NCMDS || inet6ctlerrmap[cmd] == 0))
 1217                 return;
 1218 
 1219         /* if the parameter is from icmp6, decode it. */
 1220         if (d != NULL) {
 1221                 ip6cp = (struct ip6ctlparam *)d;
 1222                 m = ip6cp->ip6c_m;
 1223                 ip6 = ip6cp->ip6c_ip6;
 1224                 off = ip6cp->ip6c_off;
 1225                 sa6_src = ip6cp->ip6c_src;
 1226         } else {
 1227                 m = NULL;
 1228                 ip6 = NULL;
 1229                 off = 0;        /* fool gcc */
 1230                 sa6_src = &sa6_any;
 1231         }
 1232 
 1233         if (ip6 != NULL) {
 1234                 struct in_conninfo inc;
 1235                 /*
 1236                  * XXX: We assume that when IPV6 is non NULL,
 1237                  * M and OFF are valid.
 1238                  */
 1239 
 1240                 /* check if we can safely examine src and dst ports */
 1241                 if (m->m_pkthdr.len < off + sizeof(*thp))
 1242                         return;
 1243 
 1244                 bzero(&th, sizeof(th));
 1245                 m_copydata(m, off, sizeof(*thp), (caddr_t)&th);
 1246 
 1247                 in6_pcbnotify(&tcbinfo, sa, th.th_dport,
 1248                     (struct sockaddr *)ip6cp->ip6c_src,
 1249                     th.th_sport, cmd, NULL, notify);
 1250 
 1251                 inc.inc_fport = th.th_dport;
 1252                 inc.inc_lport = th.th_sport;
 1253                 inc.inc6_faddr = ((struct sockaddr_in6 *)sa)->sin6_addr;
 1254                 inc.inc6_laddr = ip6cp->ip6c_src->sin6_addr;
 1255                 inc.inc_isipv6 = 1;
 1256                 INP_INFO_WLOCK(&tcbinfo);
 1257                 syncache_unreach(&inc, &th);
 1258                 INP_INFO_WUNLOCK(&tcbinfo);
 1259         } else
 1260                 in6_pcbnotify(&tcbinfo, sa, 0, (const struct sockaddr *)sa6_src,
 1261                               0, cmd, NULL, notify);
 1262 }
 1263 #endif /* INET6 */
 1264 
 1265 
 1266 /*
 1267  * Following is where TCP initial sequence number generation occurs.
 1268  *
 1269  * There are two places where we must use initial sequence numbers:
 1270  * 1.  In SYN-ACK packets.
 1271  * 2.  In SYN packets.
 1272  *
 1273  * All ISNs for SYN-ACK packets are generated by the syncache.  See
 1274  * tcp_syncache.c for details.
 1275  *
 1276  * The ISNs in SYN packets must be monotonic; TIME_WAIT recycling
 1277  * depends on this property.  In addition, these ISNs should be
 1278  * unguessable so as to prevent connection hijacking.  To satisfy
 1279  * the requirements of this situation, the algorithm outlined in
 1280  * RFC 1948 is used, with only small modifications.
 1281  *
 1282  * Implementation details:
 1283  *
 1284  * Time is based off the system timer, and is corrected so that it
 1285  * increases by one megabyte per second.  This allows for proper
 1286  * recycling on high speed LANs while still leaving over an hour
 1287  * before rollover.
 1288  *
 1289  * As reading the *exact* system time is too expensive to be done
 1290  * whenever setting up a TCP connection, we increment the time
 1291  * offset in two ways.  First, a small random positive increment
 1292  * is added to isn_offset for each connection that is set up.
 1293  * Second, the function tcp_isn_tick fires once per clock tick
 1294  * and increments isn_offset as necessary so that sequence numbers
 1295  * are incremented at approximately ISN_BYTES_PER_SECOND.  The
 1296  * random positive increments serve only to ensure that the same
 1297  * exact sequence number is never sent out twice (as could otherwise
 1298  * happen when a port is recycled in less than the system tick
 1299  * interval.)
 1300  *
 1301  * net.inet.tcp.isn_reseed_interval controls the number of seconds
 1302  * between seeding of isn_secret.  This is normally set to zero,
 1303  * as reseeding should not be necessary.
 1304  *
 1305  * Locking of the global variables isn_secret, isn_last_reseed, isn_offset,
 1306  * isn_offset_old, and isn_ctx is performed using the TCP pcbinfo lock.  In
 1307  * general, this means holding an exclusive (write) lock.
 1308  */
 1309 
 1310 #define ISN_BYTES_PER_SECOND 1048576
 1311 #define ISN_STATIC_INCREMENT 4096
 1312 #define ISN_RANDOM_INCREMENT (4096 - 1)
 1313 
 1314 static u_char isn_secret[32];
 1315 static int isn_last_reseed;
 1316 static u_int32_t isn_offset, isn_offset_old;
 1317 static MD5_CTX isn_ctx;
 1318 
 1319 tcp_seq
 1320 tcp_new_isn(tp)
 1321         struct tcpcb *tp;
 1322 {
 1323         u_int32_t md5_buffer[4];
 1324         tcp_seq new_isn;
 1325 
 1326         INP_INFO_WLOCK_ASSERT(&tcbinfo);
 1327         INP_LOCK_ASSERT(tp->t_inpcb);
 1328 
 1329         /* Seed if this is the first use, reseed if requested. */
 1330         if ((isn_last_reseed == 0) || ((tcp_isn_reseed_interval > 0) &&
 1331              (((u_int)isn_last_reseed + (u_int)tcp_isn_reseed_interval*hz)
 1332                 < (u_int)ticks))) {
 1333                 read_random(&isn_secret, sizeof(isn_secret));
 1334                 isn_last_reseed = ticks;
 1335         }
 1336 
 1337         /* Compute the md5 hash and return the ISN. */
 1338         MD5Init(&isn_ctx);
 1339         MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_fport, sizeof(u_short));
 1340         MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_lport, sizeof(u_short));
 1341 #ifdef INET6
 1342         if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) {
 1343                 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_faddr,
 1344                           sizeof(struct in6_addr));
 1345                 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_laddr,
 1346                           sizeof(struct in6_addr));
 1347         } else
 1348 #endif
 1349         {
 1350                 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_faddr,
 1351                           sizeof(struct in_addr));
 1352                 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_laddr,
 1353                           sizeof(struct in_addr));
 1354         }
 1355         MD5Update(&isn_ctx, (u_char *) &isn_secret, sizeof(isn_secret));
 1356         MD5Final((u_char *) &md5_buffer, &isn_ctx);
 1357         new_isn = (tcp_seq) md5_buffer[0];
 1358         isn_offset += ISN_STATIC_INCREMENT +
 1359                 (arc4random() & ISN_RANDOM_INCREMENT);
 1360         new_isn += isn_offset;
 1361         return (new_isn);
 1362 }
 1363 
 1364 /*
 1365  * Increment the offset to the next ISN_BYTES_PER_SECOND / hz boundary
 1366  * to keep time flowing at a relatively constant rate.  If the random
 1367  * increments have already pushed us past the projected offset, do nothing.
 1368  */
 1369 static void
 1370 tcp_isn_tick(xtp)
 1371         void *xtp;
 1372 {
 1373         u_int32_t projected_offset;
 1374 
 1375         INP_INFO_WLOCK(&tcbinfo);
 1376         projected_offset = isn_offset_old + ISN_BYTES_PER_SECOND / 100;
 1377 
 1378         if (projected_offset > isn_offset)
 1379                 isn_offset = projected_offset;
 1380 
 1381         isn_offset_old = isn_offset;
 1382         callout_reset(&isn_callout, hz/100, tcp_isn_tick, NULL);
 1383         INP_INFO_WUNLOCK(&tcbinfo);
 1384 }
 1385 
 1386 /*
 1387  * When a source quench is received, close congestion window
 1388  * to one segment.  We will gradually open it again as we proceed.
 1389  */
 1390 struct inpcb *
 1391 tcp_quench(inp, errno)
 1392         struct inpcb *inp;
 1393         int errno;
 1394 {
 1395         struct tcpcb *tp = intotcpcb(inp);
 1396 
 1397         INP_LOCK_ASSERT(inp);
 1398         if (tp != NULL)
 1399                 tp->snd_cwnd = tp->t_maxseg;
 1400         return (inp);
 1401 }
 1402 
 1403 /*
 1404  * When a specific ICMP unreachable message is received and the
 1405  * connection state is SYN-SENT, drop the connection.  This behavior
 1406  * is controlled by the icmp_may_rst sysctl.
 1407  */
 1408 struct inpcb *
 1409 tcp_drop_syn_sent(inp, errno)
 1410         struct inpcb *inp;
 1411         int errno;
 1412 {
 1413         struct tcpcb *tp = intotcpcb(inp);
 1414 
 1415         INP_LOCK_ASSERT(inp);
 1416         if (tp != NULL && tp->t_state == TCPS_SYN_SENT) {
 1417                 tcp_drop(tp, errno);
 1418                 return (NULL);
 1419         }
 1420         return (inp);
 1421 }
 1422 
 1423 /*
 1424  * When `need fragmentation' ICMP is received, update our idea of the MSS
 1425  * based on the new value in the route.  Also nudge TCP to send something,
 1426  * since we know the packet we just sent was dropped.
 1427  * This duplicates some code in the tcp_mss() function in tcp_input.c.
 1428  */
 1429 struct inpcb *
 1430 tcp_mtudisc(inp, errno)
 1431         struct inpcb *inp;
 1432         int errno;
 1433 {
 1434         struct tcpcb *tp = intotcpcb(inp);
 1435         struct rmxp_tao tao;
 1436         struct socket *so = inp->inp_socket;
 1437         u_int maxmtu;
 1438         u_int romtu;
 1439         int mss;
 1440 #ifdef INET6
 1441         int isipv6;
 1442 #endif /* INET6 */
 1443         bzero(&tao, sizeof(tao));
 1444 
 1445         INP_LOCK_ASSERT(inp);
 1446         if (tp != NULL) {
 1447 #ifdef INET6
 1448                 isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
 1449 #endif
 1450                 maxmtu = tcp_hc_getmtu(&inp->inp_inc); /* IPv4 and IPv6 */
 1451                 romtu =
 1452 #ifdef INET6
 1453                     isipv6 ? tcp_maxmtu6(&inp->inp_inc) :
 1454 #endif /* INET6 */
 1455                     tcp_maxmtu(&inp->inp_inc);
 1456                 if (!maxmtu)
 1457                         maxmtu = romtu;
 1458                 else
 1459                         maxmtu = min(maxmtu, romtu);
 1460                 if (!maxmtu) {
 1461                         tp->t_maxopd = tp->t_maxseg =
 1462 #ifdef INET6
 1463                                 isipv6 ? tcp_v6mssdflt :
 1464 #endif /* INET6 */
 1465                                 tcp_mssdflt;
 1466                         return (inp);
 1467                 }
 1468                 mss = maxmtu -
 1469 #ifdef INET6
 1470                         (isipv6 ?
 1471                          sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
 1472 #endif /* INET6 */
 1473                          sizeof(struct tcpiphdr)
 1474 #ifdef INET6
 1475                          )
 1476 #endif /* INET6 */
 1477                         ;
 1478 
 1479                 if (tcp_do_rfc1644) {
 1480                         tcp_hc_gettao(&inp->inp_inc, &tao);
 1481                         if (tao.tao_mssopt)
 1482                                 mss = min(mss, tao.tao_mssopt);
 1483                 }
 1484                 /*
 1485                  * XXX - The above conditional probably violates the TCP
 1486                  * spec.  The problem is that, since we don't know the
 1487                  * other end's MSS, we are supposed to use a conservative
 1488                  * default.  But, if we do that, then MTU discovery will
 1489                  * never actually take place, because the conservative
 1490                  * default is much less than the MTUs typically seen
 1491                  * on the Internet today.  For the moment, we'll sweep
 1492                  * this under the carpet.
 1493                  *
 1494                  * The conservative default might not actually be a problem
 1495                  * if the only case this occurs is when sending an initial
 1496                  * SYN with options and data to a host we've never talked
 1497                  * to before.  Then, they will reply with an MSS value which
 1498                  * will get recorded and the new parameters should get
 1499                  * recomputed.  For Further Study.
 1500                  */
 1501                 if (tp->t_maxopd <= mss)
 1502                         return (inp);
 1503                 tp->t_maxopd = mss;
 1504 
 1505                 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
 1506                     (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP)
 1507                         mss -= TCPOLEN_TSTAMP_APPA;
 1508                 if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
 1509                     (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC)
 1510                         mss -= TCPOLEN_CC_APPA;
 1511 #if     (MCLBYTES & (MCLBYTES - 1)) == 0
 1512                 if (mss > MCLBYTES)
 1513                         mss &= ~(MCLBYTES-1);
 1514 #else
 1515                 if (mss > MCLBYTES)
 1516                         mss = mss / MCLBYTES * MCLBYTES;
 1517 #endif
 1518                 if (so->so_snd.sb_hiwat < mss)
 1519                         mss = so->so_snd.sb_hiwat;
 1520 
 1521                 tp->t_maxseg = mss;
 1522 
 1523                 tcpstat.tcps_mturesent++;
 1524                 tp->t_rtttime = 0;
 1525                 tp->snd_nxt = tp->snd_una;
 1526                 tcp_output(tp);
 1527         }
 1528         return (inp);
 1529 }
 1530 
 1531 /*
 1532  * Look-up the routing entry to the peer of this inpcb.  If no route
 1533  * is found and it cannot be allocated, then return NULL.  This routine
 1534  * is called by TCP routines that access the rmx structure and by tcp_mss
 1535  * to get the interface MTU.
 1536  */
 1537 u_long
 1538 tcp_maxmtu(inc)
 1539         struct in_conninfo *inc;
 1540 {
 1541         struct route sro;
 1542         struct sockaddr_in *dst;
 1543         struct ifnet *ifp;
 1544         u_long maxmtu = 0;
 1545 
 1546         KASSERT(inc != NULL, ("tcp_maxmtu with NULL in_conninfo pointer"));
 1547 
 1548         bzero(&sro, sizeof(sro));
 1549         if (inc->inc_faddr.s_addr != INADDR_ANY) {
 1550                 dst = (struct sockaddr_in *)&sro.ro_dst;
 1551                 dst->sin_family = AF_INET;
 1552                 dst->sin_len = sizeof(*dst);
 1553                 dst->sin_addr = inc->inc_faddr;
 1554                 rtalloc_ign(&sro, RTF_CLONING);
 1555         }
 1556         if (sro.ro_rt != NULL) {
 1557                 ifp = sro.ro_rt->rt_ifp;
 1558                 if (sro.ro_rt->rt_rmx.rmx_mtu == 0)
 1559                         maxmtu = ifp->if_mtu;
 1560                 else
 1561                         maxmtu = min(sro.ro_rt->rt_rmx.rmx_mtu, ifp->if_mtu);
 1562                 RTFREE(sro.ro_rt);
 1563         }
 1564         return (maxmtu);
 1565 }
 1566 
 1567 #ifdef INET6
 1568 u_long
 1569 tcp_maxmtu6(inc)
 1570         struct in_conninfo *inc;
 1571 {
 1572         struct route_in6 sro6;
 1573         struct ifnet *ifp;
 1574         u_long maxmtu = 0;
 1575 
 1576         KASSERT(inc != NULL, ("tcp_maxmtu6 with NULL in_conninfo pointer"));
 1577 
 1578         bzero(&sro6, sizeof(sro6));
 1579         if (!IN6_IS_ADDR_UNSPECIFIED(&inc->inc6_faddr)) {
 1580                 sro6.ro_dst.sin6_family = AF_INET6;
 1581                 sro6.ro_dst.sin6_len = sizeof(struct sockaddr_in6);
 1582                 sro6.ro_dst.sin6_addr = inc->inc6_faddr;
 1583                 rtalloc_ign((struct route *)&sro6, RTF_CLONING);
 1584         }
 1585         if (sro6.ro_rt != NULL) {
 1586                 ifp = sro6.ro_rt->rt_ifp;
 1587                 if (sro6.ro_rt->rt_rmx.rmx_mtu == 0)
 1588                         maxmtu = IN6_LINKMTU(sro6.ro_rt->rt_ifp);
 1589                 else
 1590                         maxmtu = min(sro6.ro_rt->rt_rmx.rmx_mtu,
 1591                                      IN6_LINKMTU(sro6.ro_rt->rt_ifp));
 1592                 RTFREE(sro6.ro_rt);
 1593         }
 1594 
 1595         return (maxmtu);
 1596 }
 1597 #endif /* INET6 */
 1598 
 1599 #ifdef IPSEC
 1600 /* compute ESP/AH header size for TCP, including outer IP header. */
 1601 size_t
 1602 ipsec_hdrsiz_tcp(tp)
 1603         struct tcpcb *tp;
 1604 {
 1605         struct inpcb *inp;
 1606         struct mbuf *m;
 1607         size_t hdrsiz;
 1608         struct ip *ip;
 1609 #ifdef INET6
 1610         struct ip6_hdr *ip6;
 1611 #endif
 1612         struct tcphdr *th;
 1613 
 1614         if ((tp == NULL) || ((inp = tp->t_inpcb) == NULL))
 1615                 return (0);
 1616         MGETHDR(m, M_DONTWAIT, MT_DATA);
 1617         if (!m)
 1618                 return (0);
 1619 
 1620 #ifdef INET6
 1621         if ((inp->inp_vflag & INP_IPV6) != 0) {
 1622                 ip6 = mtod(m, struct ip6_hdr *);
 1623                 th = (struct tcphdr *)(ip6 + 1);
 1624                 m->m_pkthdr.len = m->m_len =
 1625                         sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
 1626                 tcpip_fillheaders(inp, ip6, th);
 1627                 hdrsiz = ipsec6_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp);
 1628         } else
 1629 #endif /* INET6 */
 1630         {
 1631                 ip = mtod(m, struct ip *);
 1632                 th = (struct tcphdr *)(ip + 1);
 1633                 m->m_pkthdr.len = m->m_len = sizeof(struct tcpiphdr);
 1634                 tcpip_fillheaders(inp, ip, th);
 1635                 hdrsiz = ipsec4_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp);
 1636         }
 1637 
 1638         m_free(m);
 1639         return (hdrsiz);
 1640 }
 1641 #endif /*IPSEC*/
 1642 
 1643 /*
 1644  * Move a TCP connection into TIME_WAIT state.
 1645  *    tcbinfo is locked.
 1646  *    inp is locked, and is unlocked before returning.
 1647  */
 1648 void
 1649 tcp_twstart(tp)
 1650         struct tcpcb *tp;
 1651 {
 1652         struct tcptw *tw;
 1653         struct inpcb *inp;
 1654         int tw_time, acknow;
 1655         struct socket *so;
 1656 
 1657         INP_INFO_WLOCK_ASSERT(&tcbinfo);        /* tcp_timer_2msl_reset(). */
 1658         INP_LOCK_ASSERT(tp->t_inpcb);
 1659 
 1660         tw = uma_zalloc(tcptw_zone, M_NOWAIT);
 1661         if (tw == NULL) {
 1662                 tw = tcp_timer_2msl_tw(1);
 1663                 if (tw == NULL) {
 1664                         tcp_close(tp);
 1665                         return;
 1666                 }
 1667         }
 1668         inp = tp->t_inpcb;
 1669         tw->tw_inpcb = inp;
 1670 
 1671         /*
 1672          * Recover last window size sent.
 1673          */
 1674         tw->last_win = (tp->rcv_adv - tp->rcv_nxt) >> tp->rcv_scale;
 1675 
 1676         /*
 1677          * Set t_recent if timestamps are used on the connection.
 1678          */
 1679         if ((tp->t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP|TF_NOOPT)) ==
 1680             (TF_REQ_TSTMP|TF_RCVD_TSTMP))
 1681                 tw->t_recent = tp->ts_recent;
 1682         else
 1683                 tw->t_recent = 0;
 1684 
 1685         tw->snd_nxt = tp->snd_nxt;
 1686         tw->rcv_nxt = tp->rcv_nxt;
 1687         tw->iss     = tp->iss;
 1688         tw->irs     = tp->irs;
 1689         tw->cc_recv = tp->cc_recv;
 1690         tw->cc_send = tp->cc_send;
 1691         tw->t_starttime = tp->t_starttime;
 1692         tw->tw_time = 0;
 1693 
 1694 /* XXX
 1695  * If this code will
 1696  * be used for fin-wait-2 state also, then we may need
 1697  * a ts_recent from the last segment.
 1698  */
 1699         /* Shorten TIME_WAIT [RFC-1644, p.28] */
 1700         if (tp->cc_recv != 0 && (ticks - tp->t_starttime) < tcp_msl) {
 1701                 tw_time = tp->t_rxtcur * TCPTV_TWTRUNC;
 1702                 /* For T/TCP client, force ACK now. */
 1703                 acknow = 1;
 1704         } else {
 1705                 tw_time = 2 * tcp_msl;
 1706                 acknow = tp->t_flags & TF_ACKNOW;
 1707         }
 1708         tcp_discardcb(tp);
 1709         so = inp->inp_socket;
 1710         ACCEPT_LOCK();
 1711         SOCK_LOCK(so);
 1712         so->so_pcb = NULL;
 1713         tw->tw_cred = crhold(so->so_cred);
 1714         tw->tw_so_options = so->so_options;
 1715         sotryfree(so);
 1716         inp->inp_socket = NULL;
 1717         if (acknow)
 1718                 tcp_twrespond(tw, TH_ACK);
 1719         inp->inp_ppcb = (caddr_t)tw;
 1720         inp->inp_vflag |= INP_TIMEWAIT;
 1721         tcp_timer_2msl_reset(tw, tw_time);
 1722         INP_UNLOCK(inp);
 1723 }
 1724 
 1725 /*
 1726  * The appromixate rate of ISN increase of Microsoft TCP stacks;
 1727  * the actual rate is slightly higher due to the addition of
 1728  * random positive increments.
 1729  *
 1730  * Most other new OSes use semi-randomized ISN values, so we
 1731  * do not need to worry about them.
 1732  */
 1733 #define MS_ISN_BYTES_PER_SECOND         250000
 1734 
 1735 /*
 1736  * Determine if the ISN we will generate has advanced beyond the last
 1737  * sequence number used by the previous connection.  If so, indicate
 1738  * that it is safe to recycle this tw socket by returning 1.
 1739  *
 1740  * XXXRW: This function should assert the inpcb lock as it does multiple
 1741  * non-atomic reads from the tcptw, but is currently called without it from
 1742  * in_pcb.c:in_pcblookup_local().
 1743  */
 1744 int
 1745 tcp_twrecycleable(struct tcptw *tw)
 1746 {
 1747         tcp_seq new_iss = tw->iss;
 1748         tcp_seq new_irs = tw->irs;
 1749 
 1750         new_iss += (ticks - tw->t_starttime) * (ISN_BYTES_PER_SECOND / hz);
 1751         new_irs += (ticks - tw->t_starttime) * (MS_ISN_BYTES_PER_SECOND / hz);
 1752 
 1753         if (SEQ_GT(new_iss, tw->snd_nxt) && SEQ_GT(new_irs, tw->rcv_nxt))
 1754                 return (1);
 1755         else
 1756                 return (0);
 1757 }
 1758 
 1759 struct tcptw *
 1760 tcp_twclose(struct tcptw *tw, int reuse)
 1761 {
 1762         struct inpcb *inp;
 1763 
 1764         inp = tw->tw_inpcb;
 1765         INP_INFO_WLOCK_ASSERT(&tcbinfo);        /* tcp_timer_2msl_stop(). */
 1766         INP_LOCK_ASSERT(inp);
 1767 
 1768         tw->tw_inpcb = NULL;
 1769         tcp_timer_2msl_stop(tw);
 1770         inp->inp_ppcb = NULL;
 1771 #ifdef INET6
 1772         if (inp->inp_vflag & INP_IPV6PROTO)
 1773                 in6_pcbdetach(inp);
 1774         else
 1775 #endif
 1776                 in_pcbdetach(inp);
 1777         tcpstat.tcps_closed++;
 1778         crfree(tw->tw_cred);
 1779         tw->tw_cred = NULL;
 1780         if (reuse)
 1781                 return (tw);
 1782         uma_zfree(tcptw_zone, tw);
 1783         return (NULL);
 1784 }
 1785 
 1786 int
 1787 tcp_twrespond(struct tcptw *tw, int flags)
 1788 {
 1789         struct inpcb *inp = tw->tw_inpcb;
 1790         struct tcphdr *th;
 1791         struct mbuf *m;
 1792         struct ip *ip = NULL;
 1793         u_int8_t *optp;
 1794         u_int hdrlen, optlen;
 1795         int error;
 1796 #ifdef INET6
 1797         struct ip6_hdr *ip6 = NULL;
 1798         int isipv6 = inp->inp_inc.inc_isipv6;
 1799 #endif
 1800 
 1801         INP_LOCK_ASSERT(inp);
 1802 
 1803         m = m_gethdr(M_DONTWAIT, MT_HEADER);
 1804         if (m == NULL)
 1805                 return (ENOBUFS);
 1806         m->m_data += max_linkhdr;
 1807 
 1808 #ifdef MAC
 1809         mac_create_mbuf_from_inpcb(inp, m);
 1810 #endif
 1811 
 1812 #ifdef INET6
 1813         if (isipv6) {
 1814                 hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
 1815                 ip6 = mtod(m, struct ip6_hdr *);
 1816                 th = (struct tcphdr *)(ip6 + 1);
 1817                 tcpip_fillheaders(inp, ip6, th);
 1818         } else
 1819 #endif
 1820         {
 1821                 hdrlen = sizeof(struct tcpiphdr);
 1822                 ip = mtod(m, struct ip *);
 1823                 th = (struct tcphdr *)(ip + 1);
 1824                 tcpip_fillheaders(inp, ip, th);
 1825         }
 1826         optp = (u_int8_t *)(th + 1);
 1827 
 1828         /*
 1829          * Send a timestamp and echo-reply if both our side and our peer
 1830          * have sent timestamps in our SYN's and this is not a RST.
 1831          */
 1832         if (tw->t_recent && flags == TH_ACK) {
 1833                 u_int32_t *lp = (u_int32_t *)optp;
 1834 
 1835                 /* Form timestamp option as shown in appendix A of RFC 1323. */
 1836                 *lp++ = htonl(TCPOPT_TSTAMP_HDR);
 1837                 *lp++ = htonl(ticks);
 1838                 *lp   = htonl(tw->t_recent);
 1839                 optp += TCPOLEN_TSTAMP_APPA;
 1840         }
 1841 
 1842         /*
 1843          * Send `CC-family' options if needed, and it's not a RST.
 1844          */
 1845         if (tw->cc_recv != 0 && flags == TH_ACK) {
 1846                 u_int32_t *lp = (u_int32_t *)optp;
 1847 
 1848                 *lp++ = htonl(TCPOPT_CC_HDR(TCPOPT_CC));
 1849                 *lp   = htonl(tw->cc_send);
 1850                 optp += TCPOLEN_CC_APPA;
 1851         }
 1852         optlen = optp - (u_int8_t *)(th + 1);
 1853 
 1854         m->m_len = hdrlen + optlen;
 1855         m->m_pkthdr.len = m->m_len;
 1856 
 1857         KASSERT(max_linkhdr + m->m_len <= MHLEN, ("tcptw: mbuf too small"));
 1858 
 1859         th->th_seq = htonl(tw->snd_nxt);
 1860         th->th_ack = htonl(tw->rcv_nxt);
 1861         th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
 1862         th->th_flags = flags;
 1863         th->th_win = htons(tw->last_win);
 1864 
 1865 #ifdef INET6
 1866         if (isipv6) {
 1867                 th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(struct ip6_hdr),
 1868                     sizeof(struct tcphdr) + optlen);
 1869                 ip6->ip6_hlim = in6_selecthlim(inp, NULL);
 1870                 error = ip6_output(m, inp->in6p_outputopts, NULL,
 1871                     (tw->tw_so_options & SO_DONTROUTE), NULL, NULL, inp);
 1872         } else
 1873 #endif
 1874         {
 1875                 th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
 1876                     htons(sizeof(struct tcphdr) + optlen + IPPROTO_TCP));
 1877                 m->m_pkthdr.csum_flags = CSUM_TCP;
 1878                 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
 1879                 ip->ip_len = m->m_pkthdr.len;
 1880                 if (path_mtu_discovery)
 1881                         ip->ip_off |= IP_DF;
 1882                 error = ip_output(m, inp->inp_options, NULL,
 1883                     (tw->tw_so_options & SO_DONTROUTE), NULL, inp);
 1884         }
 1885         if (flags & TH_ACK)
 1886                 tcpstat.tcps_sndacks++;
 1887         else
 1888                 tcpstat.tcps_sndctrl++;
 1889         tcpstat.tcps_sndtotal++;
 1890         return (error);
 1891 }
 1892 
 1893 /*
 1894  * TCP BANDWIDTH DELAY PRODUCT WINDOW LIMITING
 1895  *
 1896  * This code attempts to calculate the bandwidth-delay product as a
 1897  * means of determining the optimal window size to maximize bandwidth,
 1898  * minimize RTT, and avoid the over-allocation of buffers on interfaces and
 1899  * routers.  This code also does a fairly good job keeping RTTs in check
 1900  * across slow links like modems.  We implement an algorithm which is very
 1901  * similar (but not meant to be) TCP/Vegas.  The code operates on the
 1902  * transmitter side of a TCP connection and so only effects the transmit
 1903  * side of the connection.
 1904  *
 1905  * BACKGROUND:  TCP makes no provision for the management of buffer space
 1906  * at the end points or at the intermediate routers and switches.  A TCP
 1907  * stream, whether using NewReno or not, will eventually buffer as
 1908  * many packets as it is able and the only reason this typically works is
 1909  * due to the fairly small default buffers made available for a connection
 1910  * (typicaly 16K or 32K).  As machines use larger windows and/or window
 1911  * scaling it is now fairly easy for even a single TCP connection to blow-out
 1912  * all available buffer space not only on the local interface, but on
 1913  * intermediate routers and switches as well.  NewReno makes a misguided
 1914  * attempt to 'solve' this problem by waiting for an actual failure to occur,
 1915  * then backing off, then steadily increasing the window again until another
 1916  * failure occurs, ad-infinitum.  This results in terrible oscillation that
 1917  * is only made worse as network loads increase and the idea of intentionally
 1918  * blowing out network buffers is, frankly, a terrible way to manage network
 1919  * resources.
 1920  *
 1921  * It is far better to limit the transmit window prior to the failure
 1922  * condition being achieved.  There are two general ways to do this:  First
 1923  * you can 'scan' through different transmit window sizes and locate the
 1924  * point where the RTT stops increasing, indicating that you have filled the
 1925  * pipe, then scan backwards until you note that RTT stops decreasing, then
 1926  * repeat ad-infinitum.  This method works in principle but has severe
 1927  * implementation issues due to RTT variances, timer granularity, and
 1928  * instability in the algorithm which can lead to many false positives and
 1929  * create oscillations as well as interact badly with other TCP streams
 1930  * implementing the same algorithm.
 1931  *
 1932  * The second method is to limit the window to the bandwidth delay product
 1933  * of the link.  This is the method we implement.  RTT variances and our
 1934  * own manipulation of the congestion window, bwnd, can potentially
 1935  * destabilize the algorithm.  For this reason we have to stabilize the
 1936  * elements used to calculate the window.  We do this by using the minimum
 1937  * observed RTT, the long term average of the observed bandwidth, and
 1938  * by adding two segments worth of slop.  It isn't perfect but it is able
 1939  * to react to changing conditions and gives us a very stable basis on
 1940  * which to extend the algorithm.
 1941  */
 1942 void
 1943 tcp_xmit_bandwidth_limit(struct tcpcb *tp, tcp_seq ack_seq)
 1944 {
 1945         u_long bw;
 1946         u_long bwnd;
 1947         int save_ticks;
 1948 
 1949         INP_LOCK_ASSERT(tp->t_inpcb);
 1950 
 1951         /*
 1952          * If inflight_enable is disabled in the middle of a tcp connection,
 1953          * make sure snd_bwnd is effectively disabled.
 1954          */
 1955         if (tcp_inflight_enable == 0) {
 1956                 tp->snd_bwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
 1957                 tp->snd_bandwidth = 0;
 1958                 return;
 1959         }
 1960 
 1961         /*
 1962          * Figure out the bandwidth.  Due to the tick granularity this
 1963          * is a very rough number and it MUST be averaged over a fairly
 1964          * long period of time.  XXX we need to take into account a link
 1965          * that is not using all available bandwidth, but for now our
 1966          * slop will ramp us up if this case occurs and the bandwidth later
 1967          * increases.
 1968          *
 1969          * Note: if ticks rollover 'bw' may wind up negative.  We must
 1970          * effectively reset t_bw_rtttime for this case.
 1971          */
 1972         save_ticks = ticks;
 1973         if ((u_int)(save_ticks - tp->t_bw_rtttime) < 1)
 1974                 return;
 1975 
 1976         bw = (int64_t)(ack_seq - tp->t_bw_rtseq) * hz /
 1977             (save_ticks - tp->t_bw_rtttime);
 1978         tp->t_bw_rtttime = save_ticks;
 1979         tp->t_bw_rtseq = ack_seq;
 1980         if (tp->t_bw_rtttime == 0 || (int)bw < 0)
 1981                 return;
 1982         bw = ((int64_t)tp->snd_bandwidth * 15 + bw) >> 4;
 1983 
 1984         tp->snd_bandwidth = bw;
 1985 
 1986         /*
 1987          * Calculate the semi-static bandwidth delay product, plus two maximal
 1988          * segments.  The additional slop puts us squarely in the sweet
 1989          * spot and also handles the bandwidth run-up case and stabilization.
 1990          * Without the slop we could be locking ourselves into a lower
 1991          * bandwidth.
 1992          *
 1993          * Situations Handled:
 1994          *      (1) Prevents over-queueing of packets on LANs, especially on
 1995          *          high speed LANs, allowing larger TCP buffers to be
 1996          *          specified, and also does a good job preventing
 1997          *          over-queueing of packets over choke points like modems
 1998          *          (at least for the transmit side).
 1999          *
 2000          *      (2) Is able to handle changing network loads (bandwidth
 2001          *          drops so bwnd drops, bandwidth increases so bwnd
 2002          *          increases).
 2003          *
 2004          *      (3) Theoretically should stabilize in the face of multiple
 2005          *          connections implementing the same algorithm (this may need
 2006          *          a little work).
 2007          *
 2008          *      (4) Stability value (defaults to 20 = 2 maximal packets) can
 2009          *          be adjusted with a sysctl but typically only needs to be
 2010          *          on very slow connections.  A value no smaller then 5
 2011          *          should be used, but only reduce this default if you have
 2012          *          no other choice.
 2013          */
 2014 #define USERTT  ((tp->t_srtt + tp->t_rttbest) / 2)
 2015         bwnd = (int64_t)bw * USERTT / (hz << TCP_RTT_SHIFT) + tcp_inflight_stab * tp->t_maxseg / 10;
 2016 #undef USERTT
 2017 
 2018         if (tcp_inflight_debug > 0) {
 2019                 static int ltime;
 2020                 if ((u_int)(ticks - ltime) >= hz / tcp_inflight_debug) {
 2021                         ltime = ticks;
 2022                         printf("%p bw %ld rttbest %d srtt %d bwnd %ld\n",
 2023                             tp,
 2024                             bw,
 2025                             tp->t_rttbest,
 2026                             tp->t_srtt,
 2027                             bwnd
 2028                         );
 2029                 }
 2030         }
 2031         if ((long)bwnd < tcp_inflight_min)
 2032                 bwnd = tcp_inflight_min;
 2033         if (bwnd > tcp_inflight_max)
 2034                 bwnd = tcp_inflight_max;
 2035         if ((long)bwnd < tp->t_maxseg * 2)
 2036                 bwnd = tp->t_maxseg * 2;
 2037         tp->snd_bwnd = bwnd;
 2038 }
 2039 
 2040 #ifdef TCP_SIGNATURE
 2041 /*
 2042  * Callback function invoked by m_apply() to digest TCP segment data
 2043  * contained within an mbuf chain.
 2044  */
 2045 static int
 2046 tcp_signature_apply(void *fstate, void *data, u_int len)
 2047 {
 2048 
 2049         MD5Update(fstate, (u_char *)data, len);
 2050         return (0);
 2051 }
 2052 
 2053 /*
 2054  * Compute TCP-MD5 hash of a TCPv4 segment. (RFC2385)
 2055  *
 2056  * Parameters:
 2057  * m            pointer to head of mbuf chain
 2058  * off0         offset to TCP header within the mbuf chain
 2059  * len          length of TCP segment data, excluding options
 2060  * optlen       length of TCP segment options
 2061  * buf          pointer to storage for computed MD5 digest
 2062  * direction    direction of flow (IPSEC_DIR_INBOUND or OUTBOUND)
 2063  *
 2064  * We do this over ip, tcphdr, segment data, and the key in the SADB.
 2065  * When called from tcp_input(), we can be sure that th_sum has been
 2066  * zeroed out and verified already.
 2067  *
 2068  * This function is for IPv4 use only. Calling this function with an
 2069  * IPv6 packet in the mbuf chain will yield undefined results.
 2070  *
 2071  * Return 0 if successful, otherwise return -1.
 2072  *
 2073  * XXX The key is retrieved from the system's PF_KEY SADB, by keying a
 2074  * search with the destination IP address, and a 'magic SPI' to be
 2075  * determined by the application. This is hardcoded elsewhere to 1179
 2076  * right now. Another branch of this code exists which uses the SPD to
 2077  * specify per-application flows but it is unstable.
 2078  */
 2079 int
 2080 tcp_signature_compute(struct mbuf *m, int off0, int len, int optlen,
 2081     u_char *buf, u_int direction)
 2082 {
 2083         union sockaddr_union dst;
 2084         struct ippseudo ippseudo;
 2085         MD5_CTX ctx;
 2086         int doff;
 2087         struct ip *ip;
 2088         struct ipovly *ipovly;
 2089         struct secasvar *sav;
 2090         struct tcphdr *th;
 2091         u_short savecsum;
 2092 
 2093         KASSERT(m != NULL, ("NULL mbuf chain"));
 2094         KASSERT(buf != NULL, ("NULL signature pointer"));
 2095 
 2096         /* Extract the destination from the IP header in the mbuf. */
 2097         ip = mtod(m, struct ip *);
 2098         bzero(&dst, sizeof(union sockaddr_union));
 2099         dst.sa.sa_len = sizeof(struct sockaddr_in);
 2100         dst.sa.sa_family = AF_INET;
 2101         dst.sin.sin_addr = (direction == IPSEC_DIR_INBOUND) ?
 2102             ip->ip_src : ip->ip_dst;
 2103 
 2104         /* Look up an SADB entry which matches the address of the peer. */
 2105         sav = KEY_ALLOCSA(&dst, IPPROTO_TCP, htonl(TCP_SIG_SPI));
 2106         if (sav == NULL) {
 2107                 printf("%s: SADB lookup failed for %s\n", __func__,
 2108                     inet_ntoa(dst.sin.sin_addr));
 2109                 return (EINVAL);
 2110         }
 2111 
 2112         MD5Init(&ctx);
 2113         ipovly = (struct ipovly *)ip;
 2114         th = (struct tcphdr *)((u_char *)ip + off0);
 2115         doff = off0 + sizeof(struct tcphdr) + optlen;
 2116 
 2117         /*
 2118          * Step 1: Update MD5 hash with IP pseudo-header.
 2119          *
 2120          * XXX The ippseudo header MUST be digested in network byte order,
 2121          * or else we'll fail the regression test. Assume all fields we've
 2122          * been doing arithmetic on have been in host byte order.
 2123          * XXX One cannot depend on ipovly->ih_len here. When called from
 2124          * tcp_output(), the underlying ip_len member has not yet been set.
 2125          */
 2126         ippseudo.ippseudo_src = ipovly->ih_src;
 2127         ippseudo.ippseudo_dst = ipovly->ih_dst;
 2128         ippseudo.ippseudo_pad = 0;
 2129         ippseudo.ippseudo_p = IPPROTO_TCP;
 2130         ippseudo.ippseudo_len = htons(len + sizeof(struct tcphdr) + optlen);
 2131         MD5Update(&ctx, (char *)&ippseudo, sizeof(struct ippseudo));
 2132 
 2133         /*
 2134          * Step 2: Update MD5 hash with TCP header, excluding options.
 2135          * The TCP checksum must be set to zero.
 2136          */
 2137         savecsum = th->th_sum;
 2138         th->th_sum = 0;
 2139         MD5Update(&ctx, (char *)th, sizeof(struct tcphdr));
 2140         th->th_sum = savecsum;
 2141 
 2142         /*
 2143          * Step 3: Update MD5 hash with TCP segment data.
 2144          *         Use m_apply() to avoid an early m_pullup().
 2145          */
 2146         if (len > 0)
 2147                 m_apply(m, doff, len, tcp_signature_apply, &ctx);
 2148 
 2149         /*
 2150          * Step 4: Update MD5 hash with shared secret.
 2151          */
 2152         MD5Update(&ctx, _KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
 2153         MD5Final(buf, &ctx);
 2154 
 2155         key_sa_recordxfer(sav, m);
 2156         KEY_FREESAV(&sav);
 2157         return (0);
 2158 }
 2159 #endif /* TCP_SIGNATURE */
 2160 
 2161 static int
 2162 sysctl_drop(SYSCTL_HANDLER_ARGS)
 2163 {
 2164         /* addrs[0] is a foreign socket, addrs[1] is a local one. */
 2165         struct sockaddr_storage addrs[2];
 2166         struct inpcb *inp;
 2167         struct tcpcb *tp;
 2168         struct sockaddr_in *fin, *lin;
 2169 #ifdef INET6
 2170         struct sockaddr_in6 *fin6, *lin6;
 2171         struct in6_addr f6, l6;
 2172 #endif
 2173         int error;
 2174 
 2175         inp = NULL;
 2176         fin = lin = NULL;
 2177 #ifdef INET6
 2178         fin6 = lin6 = NULL;
 2179 #endif
 2180         error = 0;
 2181 
 2182         if (req->oldptr != NULL || req->oldlen != 0)
 2183                 return (EINVAL);
 2184         if (req->newptr == NULL)
 2185                 return (EPERM);
 2186         if (req->newlen < sizeof(addrs))
 2187                 return (ENOMEM);
 2188         error = SYSCTL_IN(req, &addrs, sizeof(addrs));
 2189         if (error)
 2190                 return (error);
 2191 
 2192         switch (addrs[0].ss_family) {
 2193 #ifdef INET6
 2194         case AF_INET6:
 2195                 fin6 = (struct sockaddr_in6 *)&addrs[0];
 2196                 lin6 = (struct sockaddr_in6 *)&addrs[1];
 2197                 if (fin6->sin6_len != sizeof(struct sockaddr_in6) ||
 2198                     lin6->sin6_len != sizeof(struct sockaddr_in6))
 2199                         return (EINVAL);
 2200                 if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) {
 2201                         if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr))
 2202                                 return (EINVAL);
 2203                         in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]);
 2204                         in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]);
 2205                         fin = (struct sockaddr_in *)&addrs[0];
 2206                         lin = (struct sockaddr_in *)&addrs[1];
 2207                         break;
 2208                 }
 2209                 error = in6_embedscope(&f6, fin6, NULL, NULL);
 2210                 if (error)
 2211                         return (EINVAL);
 2212                 error = in6_embedscope(&l6, lin6, NULL, NULL);
 2213                 if (error)
 2214                         return (EINVAL);
 2215                 break;
 2216 #endif
 2217         case AF_INET:
 2218                 fin = (struct sockaddr_in *)&addrs[0];
 2219                 lin = (struct sockaddr_in *)&addrs[1];
 2220                 if (fin->sin_len != sizeof(struct sockaddr_in) ||
 2221                     lin->sin_len != sizeof(struct sockaddr_in))
 2222                         return (EINVAL);
 2223                 break;
 2224         default:
 2225                 return (EINVAL);
 2226         }
 2227         INP_INFO_WLOCK(&tcbinfo);
 2228         switch (addrs[0].ss_family) {
 2229 #ifdef INET6
 2230         case AF_INET6:
 2231                 inp = in6_pcblookup_hash(&tcbinfo, &f6, fin6->sin6_port,
 2232                     &l6, lin6->sin6_port, 0, NULL);
 2233                 break;
 2234 #endif
 2235         case AF_INET:
 2236                 inp = in_pcblookup_hash(&tcbinfo, fin->sin_addr, fin->sin_port,
 2237                     lin->sin_addr, lin->sin_port, 0, NULL);
 2238                 break;
 2239         }
 2240         if (inp != NULL) {
 2241                 INP_LOCK(inp);
 2242                 if ((tp = intotcpcb(inp)) &&
 2243                     ((inp->inp_socket->so_options & SO_ACCEPTCONN) == 0)) {
 2244                         tp = tcp_drop(tp, ECONNABORTED);
 2245                         if (tp != NULL)
 2246                                 INP_UNLOCK(inp);
 2247                 } else
 2248                         INP_UNLOCK(inp);
 2249         } else
 2250                 error = ESRCH;
 2251         INP_INFO_WUNLOCK(&tcbinfo);
 2252         return (error);
 2253 }
 2254 
 2255 SYSCTL_PROC(_net_inet_tcp, TCPCTL_DROP, drop,
 2256     CTLTYPE_STRUCT|CTLFLAG_WR|CTLFLAG_SKIP, NULL,
 2257     0, sysctl_drop, "", "Drop TCP connection");

Cache object: 0408dc8a010403b1e606fb4847b68fda


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.