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

Cache object: 26b4d90a75a29148d2d544e3238a2fb7


[ 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.