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