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