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