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

Cache object: 65ef3de7d0405ba8ea42113a6fc36150


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