Debian Codegraph @

tcpip/transport/tcp/accept.go

raw symbols SCIP
1 // Copyright 2018 The gVisor Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package tcp
16
17 import (
18 "container/list"
19 "crypto/sha1"
20 "encoding/binary"
21 "fmt"
22 "hash"
23 "io"
24 "time"
25
26 "inet.af/netstack/sleep"
27 "inet.af/netstack/sync"
28 "inet.af/netstack/tcpip"
29 "inet.af/netstack/tcpip/header"
30 "inet.af/netstack/tcpip/ports"
31 "inet.af/netstack/tcpip/seqnum"
32 "inet.af/netstack/tcpip/stack"
33 "inet.af/netstack/waiter"
34 )
35
36 const (
37 // tsLen is the length, in bits, of the timestamp in the SYN cookie.
38 tsLen = 8
39
40 // tsMask is a mask for timestamp values (i.e., tsLen bits).
41 tsMask = (1 << tsLen) - 1
42
43 // tsOffset is the offset, in bits, of the timestamp in the SYN cookie.
44 tsOffset = 24
45
46 // hashMask is the mask for hash values (i.e., tsOffset bits).
47 hashMask = (1 << tsOffset) - 1
48
49 // maxTSDiff is the maximum allowed difference between a received cookie
50 // timestamp and the current timestamp. If the difference is greater
51 // than maxTSDiff, the cookie is expired.
52 maxTSDiff = 2
53 )
54
55 var (
56 // mssTable is a slice containing the possible MSS values that we
57 // encode in the SYN cookie with two bits.
58 mssTable = []uint16{536, 1300, 1440, 1460}
59 )
60
61 func encodeMSS(mss uint16) uint32 {
62 for i := len(mssTable) - 1; i > 0; i-- {
63 if mss >= mssTable[i] {
64 return uint32(i)
65 }
66 }
67 return 0
68 }
69
70 // listenContext is used by a listening endpoint to store state used while
71 // listening for connections. This struct is allocated by the listen goroutine
72 // and must not be accessed or have its methods called concurrently as they
73 // may mutate the stored objects.
74 type listenContext struct {
75 stack *stack.Stack
76 protocol *protocol
77
78 // rcvWnd is the receive window that is sent by this listening context
79 // in the initial SYN-ACK.
80 rcvWnd seqnum.Size
81
82 // nonce are random bytes that are initialized once when the context
83 // is created and used to seed the hash function when generating
84 // the SYN cookie.
85 nonce [2][sha1.BlockSize]byte
86
87 // listenEP is a reference to the listening endpoint associated with
88 // this context. Can be nil if the context is created by the forwarder.
89 listenEP *endpoint
90
91 // hasherMu protects hasher.
92 hasherMu sync.Mutex
93 // hasher is the hash function used to generate a SYN cookie.
94 hasher hash.Hash
95
96 // v6Only is true if listenEP is a dual stack socket and has the
97 // IPV6_V6ONLY option set.
98 v6Only bool
99
100 // netProto indicates the network protocol(IPv4/v6) for the listening
101 // endpoint.
102 netProto tcpip.NetworkProtocolNumber
103 }
104
105 // timeStamp returns an 8-bit timestamp with a granularity of 64 seconds.
106 func timeStamp(clock tcpip.Clock) uint32 {
107 return uint32(clock.NowMonotonic().Sub(tcpip.MonotonicTime{}).Seconds()) >> 6 & tsMask
108 }
109
110 // newListenContext creates a new listen context.
111 func newListenContext(stk *stack.Stack, protocol *protocol, listenEP *endpoint, rcvWnd seqnum.Size, v6Only bool, netProto tcpip.NetworkProtocolNumber) *listenContext {
112 l := &listenContext{
113 stack: stk,
114 protocol: protocol,
115 rcvWnd: rcvWnd,
116 hasher: sha1.New(),
117 v6Only: v6Only,
118 netProto: netProto,
119 listenEP: listenEP,
120 }
121
122 for i := range l.nonce {
123 if _, err := io.ReadFull(stk.SecureRNG(), l.nonce[i][:]); err != nil {
124 panic(err)
125 }
126 }
127
128 return l
129 }
130
131 // cookieHash calculates the cookieHash for the given id, timestamp and nonce
132 // index. The hash is used to create and validate cookies.
133 func (l *listenContext) cookieHash(id stack.TransportEndpointID, ts uint32, nonceIndex int) uint32 {
134
135 // Initialize block with fixed-size data: local ports and v.
136 var payload [8]byte
137 binary.BigEndian.PutUint16(payload[0:], id.LocalPort)
138 binary.BigEndian.PutUint16(payload[2:], id.RemotePort)
139 binary.BigEndian.PutUint32(payload[4:], ts)
140
141 // Feed everything to the hasher.
142 l.hasherMu.Lock()
143 l.hasher.Reset()
144
145 // Per hash.Hash.Writer:
146 //
147 // It never returns an error.
148 l.hasher.Write(payload[:])
149 l.hasher.Write(l.nonce[nonceIndex][:])
150 l.hasher.Write([]byte(id.LocalAddress))
151 l.hasher.Write([]byte(id.RemoteAddress))
152
153 // Finalize the calculation of the hash and return the first 4 bytes.
154 h := l.hasher.Sum(nil)
155 l.hasherMu.Unlock()
156
157 return binary.BigEndian.Uint32(h[:])
158 }
159
160 // createCookie creates a SYN cookie for the given id and incoming sequence
161 // number.
162 func (l *listenContext) createCookie(id stack.TransportEndpointID, seq seqnum.Value, data uint32) seqnum.Value {
163 ts := timeStamp(l.stack.Clock())
164 v := l.cookieHash(id, 0, 0) + uint32(seq) + (ts << tsOffset)
165 v += (l.cookieHash(id, ts, 1) + data) & hashMask
166 return seqnum.Value(v)
167 }
168
169 // isCookieValid checks if the supplied cookie is valid for the given id and
170 // sequence number. If it is, it also returns the data originally encoded in the
171 // cookie when createCookie was called.
172 func (l *listenContext) isCookieValid(id stack.TransportEndpointID, cookie seqnum.Value, seq seqnum.Value) (uint32, bool) {
173 ts := timeStamp(l.stack.Clock())
174 v := uint32(cookie) - l.cookieHash(id, 0, 0) - uint32(seq)
175 cookieTS := v >> tsOffset
176 if ((ts - cookieTS) & tsMask) > maxTSDiff {
177 return 0, false
178 }
179
180 return (v - l.cookieHash(id, cookieTS, 1)) & hashMask, true
181 }
182
183 // createConnectingEndpoint creates a new endpoint in a connecting state, with
184 // the connection parameters given by the arguments.
185 func (l *listenContext) createConnectingEndpoint(s *segment, rcvdSynOpts header.TCPSynOptions, queue *waiter.Queue) (*endpoint, tcpip.Error) {
186 // Create a new endpoint.
187 netProto := l.netProto
188 if netProto == 0 {
189 netProto = s.netProto
190 }
191
192 route, err := l.stack.FindRoute(s.nicID, s.dstAddr, s.srcAddr, s.netProto, false /* multicastLoop */)
193 if err != nil {
194 return nil, err
195 }
196
197 n := newEndpoint(l.stack, l.protocol, netProto, queue)
198 n.ops.SetV6Only(l.v6Only)
199 n.TransportEndpointInfo.ID = s.id
200 n.boundNICID = s.nicID
201 n.route = route
202 n.effectiveNetProtos = []tcpip.NetworkProtocolNumber{s.netProto}
203 n.ops.SetReceiveBufferSize(int64(l.rcvWnd), false /* notify */)
204 n.amss = calculateAdvertisedMSS(n.userMSS, n.route)
205 n.setEndpointState(StateConnecting)
206
207 n.maybeEnableTimestamp(rcvdSynOpts)
208 n.maybeEnableSACKPermitted(rcvdSynOpts)
209
210 n.initGSO()
211
212 // Bootstrap the auto tuning algorithm. Starting at zero will result in
213 // a large step function on the first window adjustment causing the
214 // window to grow to a really large value.
215 n.rcvQueueInfo.RcvAutoParams.PrevCopiedBytes = n.initialReceiveWindow()
216
217 return n, nil
218 }
219
220 // startHandshake creates a new endpoint in connecting state and then sends
221 // the SYN-ACK for the TCP 3-way handshake. It returns the state of the
222 // handshake in progress, which includes the new endpoint in the SYN-RCVD
223 // state.
224 //
225 // On success, a handshake h is returned with h.ep.mu held.
226 //
227 // Precondition: if l.listenEP != nil, l.listenEP.mu must be locked.
228 func (l *listenContext) startHandshake(s *segment, opts header.TCPSynOptions, queue *waiter.Queue, owner tcpip.PacketOwner) (*handshake, tcpip.Error) {
229 // Create new endpoint.
230 irs := s.sequenceNumber
231 isn := generateSecureISN(s.id, l.stack.Clock(), l.protocol.seqnumSecret)
232 ep, err := l.createConnectingEndpoint(s, opts, queue)
233 if err != nil {
234 return nil, err
235 }
236
237 // Lock the endpoint before registering to ensure that no out of
238 // band changes are possible due to incoming packets etc till
239 // the endpoint is done initializing.
240 ep.mu.Lock()
241 ep.owner = owner
242
243 // listenEP is nil when listenContext is used by tcp.Forwarder.
244 deferAccept := time.Duration(0)
245 if l.listenEP != nil {
246 if l.listenEP.EndpointState() != StateListen {
247
248 // Ensure we release any registrations done by the newly
249 // created endpoint.
250 ep.mu.Unlock()
251 ep.Close()
252
253 return nil, &tcpip.ErrConnectionAborted{}
254 }
255
256 // Propagate any inheritable options from the listening endpoint
257 // to the newly created endpoint.
258 l.listenEP.propagateInheritableOptionsLocked(ep) // +checklocksforce
259
260 if !ep.reserveTupleLocked() {
261 ep.mu.Unlock()
262 ep.Close()
263
264 return nil, &tcpip.ErrConnectionAborted{}
265 }
266
267 deferAccept = l.listenEP.deferAccept
268 }
269
270 // Register new endpoint so that packets are routed to it.
271 if err := ep.stack.RegisterTransportEndpoint(
272 ep.effectiveNetProtos,
273 ProtocolNumber,
274 ep.TransportEndpointInfo.ID,
275 ep,
276 ep.boundPortFlags,
277 ep.boundBindToDevice,
278 ); err != nil {
279 ep.mu.Unlock()
280 ep.Close()
281
282 ep.drainClosingSegmentQueue()
283
284 return nil, err
285 }
286
287 ep.isRegistered = true
288
289 // Initialize and start the handshake.
290 h := ep.newPassiveHandshake(isn, irs, opts, deferAccept)
291 h.listenEP = l.listenEP
292 h.start()
293 return h, nil
294 }
295
296 // performHandshake performs a TCP 3-way handshake. On success, the new
297 // established endpoint is returned with e.mu held.
298 //
299 // Precondition: if l.listenEP != nil, l.listenEP.mu must be locked.
300 func (l *listenContext) performHandshake(s *segment, opts header.TCPSynOptions, queue *waiter.Queue, owner tcpip.PacketOwner) (*endpoint, tcpip.Error) {
301 h, err := l.startHandshake(s, opts, queue, owner)
302 if err != nil {
303 return nil, err
304 }
305 ep := h.ep
306
307 // N.B. the endpoint is generated above by startHandshake, and will be
308 // returned locked. This first call is forced.
309 if err := h.complete(); err != nil { // +checklocksforce
310 ep.stack.Stats().TCP.FailedConnectionAttempts.Increment()
311 ep.stats.FailedConnectionAttempts.Increment()
312 l.cleanupFailedHandshake(h)
313 return nil, err
314 }
315 l.cleanupCompletedHandshake(h)
316 return ep, nil
317 }
318
319 // +checklocks:h.ep.mu
320 func (l *listenContext) cleanupFailedHandshake(h *handshake) {
321 e := h.ep
322 e.mu.Unlock()
323 e.Close()
324 e.notifyAborted()
325 e.drainClosingSegmentQueue()
326 e.h = nil
327 }
328
329 // cleanupCompletedHandshake transfers any state from the completed handshake to
330 // the new endpoint.
331 //
332 // +checklocks:h.ep.mu
333 func (l *listenContext) cleanupCompletedHandshake(h *handshake) {
334 e := h.ep
335 e.isConnectNotified = true
336
337 // Update the receive window scaling. We can't do it before the
338 // handshake because it's possible that the peer doesn't support window
339 // scaling.
340 e.rcv.RcvWndScale = e.h.effectiveRcvWndScale()
341
342 // Clean up handshake state stored in the endpoint so that it can be GCed.
343 e.h = nil
344 }
345
346 // propagateInheritableOptionsLocked propagates any options set on the listening
347 // endpoint to the newly created endpoint.
348 //
349 // +checklocks:e.mu
350 // +checklocks:n.mu
351 func (e *endpoint) propagateInheritableOptionsLocked(n *endpoint) {
352 n.userTimeout = e.userTimeout
353 n.portFlags = e.portFlags
354 n.boundBindToDevice = e.boundBindToDevice
355 n.boundPortFlags = e.boundPortFlags
356 n.userMSS = e.userMSS
357 }
358
359 // reserveTupleLocked reserves an accepted endpoint's tuple.
360 //
361 // Precondition: e.propagateInheritableOptionsLocked has been called.
362 //
363 // +checklocks:e.mu
364 func (e *endpoint) reserveTupleLocked() bool {
365 dest := tcpip.FullAddress{
366 Addr: e.TransportEndpointInfo.ID.RemoteAddress,
367 Port: e.TransportEndpointInfo.ID.RemotePort,
368 }
369 portRes := ports.Reservation{
370 Networks: e.effectiveNetProtos,
371 Transport: ProtocolNumber,
372 Addr: e.TransportEndpointInfo.ID.LocalAddress,
373 Port: e.TransportEndpointInfo.ID.LocalPort,
374 Flags: e.boundPortFlags,
375 BindToDevice: e.boundBindToDevice,
376 Dest: dest,
377 }
378 if !e.stack.ReserveTuple(portRes) {
379 e.stack.Stats().TCP.FailedPortReservations.Increment()
380 return false
381 }
382
383 e.isPortReserved = true
384 e.boundDest = dest
385 return true
386 }
387
388 // notifyAborted wakes up any waiters on registered, but not accepted
389 // endpoints.
390 //
391 // This is strictly not required normally as a socket that was never accepted
392 // can't really have any registered waiters except when stack.Wait() is called
393 // which waits for all registered endpoints to stop and expects an EventHUp.
394 func (e *endpoint) notifyAborted() {
395 e.waiterQueue.Notify(waiter.EventHUp | waiter.EventErr | waiter.ReadableEvents | waiter.WritableEvents)
396 }
397
398 func (e *endpoint) acceptQueueIsFull() bool {
399 e.acceptMu.Lock()
400 full := e.acceptQueue.isFull()
401 e.acceptMu.Unlock()
402 return full
403 }
404
405 // +stateify savable
406 type acceptQueue struct {
407 // NB: this could be an endpointList, but ilist only permits endpoints to
408 // belong to one list at a time, and endpoints are already stored in the
409 // dispatcher's list.
410 endpoints list.List `state:".([]*endpoint)"`
411
412 // pendingEndpoints is a set of all endpoints for which a handshake is
413 // in progress.
414 pendingEndpoints map[*endpoint]struct{}
415
416 // capacity is the maximum number of endpoints that can be in endpoints.
417 capacity int
418 }
419
420 func (a *acceptQueue) isFull() bool {
421 return a.endpoints.Len() == a.capacity
422 }
423
424 // handleListenSegment is called when a listening endpoint receives a segment
425 // and needs to handle it.
426 //
427 // +checklocks:e.mu
428 func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) tcpip.Error {
429 e.rcvQueueInfo.rcvQueueMu.Lock()
430 rcvClosed := e.rcvQueueInfo.RcvClosed
431 e.rcvQueueInfo.rcvQueueMu.Unlock()
432 if rcvClosed || s.flags.Contains(header.TCPFlagSyn|header.TCPFlagAck) {
433 // If the endpoint is shutdown, reply with reset.
434 //
435 // RFC 793 section 3.4 page 35 (figure 12) outlines that a RST
436 // must be sent in response to a SYN-ACK while in the listen
437 // state to prevent completing a handshake from an old SYN.
438 return replyWithReset(e.stack, s, e.sendTOS, e.ttl)
439 }
440
441 switch {
442 case s.flags.Contains(header.TCPFlagRst):
443 e.stack.Stats().DroppedPackets.Increment()
444 return nil
445
446 case s.flags == header.TCPFlagSyn:
447 if e.acceptQueueIsFull() {
448 e.stack.Stats().TCP.ListenOverflowSynDrop.Increment()
449 e.stats.ReceiveErrors.ListenOverflowSynDrop.Increment()
450 e.stack.Stats().DroppedPackets.Increment()
451 return nil
452 }
453
454 opts := parseSynSegmentOptions(s)
455
456 useSynCookies, err := func() (bool, tcpip.Error) {
457 var alwaysUseSynCookies tcpip.TCPAlwaysUseSynCookies
458 if err := e.stack.TransportProtocolOption(header.TCPProtocolNumber, &alwaysUseSynCookies); err != nil {
459 panic(fmt.Sprintf("TransportProtocolOption(%d, %T) = %s", header.TCPProtocolNumber, alwaysUseSynCookies, err))
460 }
461 if alwaysUseSynCookies {
462 return true, nil
463 }
464 e.acceptMu.Lock()
465 defer e.acceptMu.Unlock()
466
467 // The capacity of the accepted queue would always be one greater than the
468 // listen backlog. But, the SYNRCVD connections count is always checked
469 // against the listen backlog value for Linux parity reason.
470 // https://github.com/torvalds/linux/blob/7acac4b3196/include/net/inet_connection_sock.h#L280
471 if len(e.acceptQueue.pendingEndpoints) == e.acceptQueue.capacity-1 {
472 return true, nil
473 }
474
475 h, err := ctx.startHandshake(s, opts, &waiter.Queue{}, e.owner)
476 if err != nil {
477 e.stack.Stats().TCP.FailedConnectionAttempts.Increment()
478 e.stats.FailedConnectionAttempts.Increment()
479 return false, err
480 }
481
482 e.acceptQueue.pendingEndpoints[h.ep] = struct{}{}
483 e.pendingAccepted.Add(1)
484
485 go func() {
486 defer func() {
487 e.pendingAccepted.Done()
488
489 e.acceptMu.Lock()
490 defer e.acceptMu.Unlock()
491 delete(e.acceptQueue.pendingEndpoints, h.ep)
492 }()
493
494 // Note that startHandshake returns a locked endpoint. The force call
495 // here just makes it so.
496 if err := h.complete(); err != nil { // +checklocksforce
497 e.stack.Stats().TCP.FailedConnectionAttempts.Increment()
498 e.stats.FailedConnectionAttempts.Increment()
499 ctx.cleanupFailedHandshake(h)
500 return
501 }
502 ctx.cleanupCompletedHandshake(h)
503 h.ep.startAcceptedLoop()
504 e.stack.Stats().TCP.PassiveConnectionOpenings.Increment()
505
506 // Deliver the endpoint to the accept queue.
507 //
508 // Drop the lock before notifying to avoid deadlock in user-specified
509 // callbacks.
510 delivered := func() bool {
511 e.acceptMu.Lock()
512 defer e.acceptMu.Unlock()
513 for {
514 // The listener is transitioning out of the Listen state; bail.
515 if e.acceptQueue.capacity == 0 {
516 return false
517 }
518 if e.acceptQueue.isFull() {
519 e.acceptCond.Wait()
520 continue
521 }
522
523 e.acceptQueue.endpoints.PushBack(h.ep)
524 return true
525 }
526 }()
527
528 if delivered {
529 e.waiterQueue.Notify(waiter.ReadableEvents)
530 } else {
531 h.ep.notifyProtocolGoroutine(notifyReset)
532 }
533 }()
534
535 return false, nil
536 }()
537 if err != nil {
538 return err
539 }
540 if !useSynCookies {
541 return nil
542 }
543
544 route, err := e.stack.FindRoute(s.nicID, s.dstAddr, s.srcAddr, s.netProto, false /* multicastLoop */)
545 if err != nil {
546 return err
547 }
548 defer route.Release()
549
550 // Send SYN without window scaling because we currently
551 // don't encode this information in the cookie.
552 //
553 // Enable Timestamp option if the original syn did have
554 // the timestamp option specified.
555 //
556 // Use the user supplied MSS on the listening socket for
557 // new connections, if available.
558 synOpts := header.TCPSynOptions{
559 WS: -1,
560 TS: opts.TS,
561 TSEcr: opts.TSVal,
562 MSS: calculateAdvertisedMSS(e.userMSS, route),
563 }
564 if opts.TS {
565 offset := e.protocol.tsOffset(s.dstAddr, s.srcAddr)
566 now := e.stack.Clock().NowMonotonic()
567 synOpts.TSVal = offset.TSVal(now)
568 }
569 cookie := ctx.createCookie(s.id, s.sequenceNumber, encodeMSS(opts.MSS))
570 fields := tcpFields{
571 id: s.id,
572 ttl: e.ttl,
573 tos: e.sendTOS,
574 flags: header.TCPFlagSyn | header.TCPFlagAck,
575 seq: cookie,
576 ack: s.sequenceNumber + 1,
577 rcvWnd: ctx.rcvWnd,
578 }
579 if err := e.sendSynTCP(route, fields, synOpts); err != nil {
580 return err
581 }
582 e.stack.Stats().TCP.ListenOverflowSynCookieSent.Increment()
583 return nil
584
585 case s.flags.Contains(header.TCPFlagAck):
586 iss := s.ackNumber - 1
587 irs := s.sequenceNumber - 1
588
589 // Since SYN cookies are in use this is potentially an ACK to a
590 // SYN-ACK we sent but don't have a half open connection state
591 // as cookies are being used to protect against a potential SYN
592 // flood. In such cases validate the cookie and if valid create
593 // a fully connected endpoint and deliver to the accept queue.
594 //
595 // If not, silently drop the ACK to avoid leaking information
596 // when under a potential syn flood attack.
597 //
598 // Validate the cookie.
599 data, ok := ctx.isCookieValid(s.id, iss, irs)
600 if !ok || int(data) >= len(mssTable) {
601 e.stack.Stats().TCP.ListenOverflowInvalidSynCookieRcvd.Increment()
602 e.stack.Stats().DroppedPackets.Increment()
603
604 // When not using SYN cookies, as per RFC 793, section 3.9, page 64:
605 // Any acknowledgment is bad if it arrives on a connection still in
606 // the LISTEN state. An acceptable reset segment should be formed
607 // for any arriving ACK-bearing segment. The RST should be
608 // formatted as follows:
609 //
610 // <SEQ=SEG.ACK><CTL=RST>
611 //
612 // Send a reset as this is an ACK for which there is no
613 // half open connections and we are not using cookies
614 // yet.
615 //
616 // The only time we should reach here when a connection
617 // was opened and closed really quickly and a delayed
618 // ACK was received from the sender.
619 return replyWithReset(e.stack, s, e.sendTOS, e.ttl)
620 }
621
622 // Keep hold of acceptMu until the new endpoint is in the accept queue (or
623 // if there is an error), to guarantee that we will keep our spot in the
624 // queue even if another handshake from the syn queue completes.
625 e.acceptMu.Lock()
626 if e.acceptQueue.isFull() {
627 // Silently drop the ack as the application can't accept
628 // the connection at this point. The ack will be
629 // retransmitted by the sender anyway and we can
630 // complete the connection at the time of retransmit if
631 // the backlog has space.
632 e.acceptMu.Unlock()
633 e.stack.Stats().TCP.ListenOverflowAckDrop.Increment()
634 e.stats.ReceiveErrors.ListenOverflowAckDrop.Increment()
635 e.stack.Stats().DroppedPackets.Increment()
636 return nil
637 }
638
639 e.stack.Stats().TCP.ListenOverflowSynCookieRcvd.Increment()
640 // Create newly accepted endpoint and deliver it.
641 rcvdSynOptions := header.TCPSynOptions{
642 MSS: mssTable[data],
643 // Disable Window scaling as original SYN is
644 // lost.
645 WS: -1,
646 }
647
648 // When syn cookies are in use we enable timestamp only
649 // if the ack specifies the timestamp option assuming
650 // that the other end did in fact negotiate the
651 // timestamp option in the original SYN.
652 if s.parsedOptions.TS {
653 rcvdSynOptions.TS = true
654 rcvdSynOptions.TSVal = s.parsedOptions.TSVal
655 rcvdSynOptions.TSEcr = s.parsedOptions.TSEcr
656 }
657
658 n, err := ctx.createConnectingEndpoint(s, rcvdSynOptions, &waiter.Queue{})
659 if err != nil {
660 e.acceptMu.Unlock()
661 return err
662 }
663
664 n.mu.Lock()
665
666 // Propagate any inheritable options from the listening endpoint
667 // to the newly created endpoint.
668 e.propagateInheritableOptionsLocked(n)
669
670 if !n.reserveTupleLocked() {
671 n.mu.Unlock()
672 e.acceptMu.Unlock()
673 n.Close()
674
675 e.stack.Stats().TCP.FailedConnectionAttempts.Increment()
676 e.stats.FailedConnectionAttempts.Increment()
677 return nil
678 }
679
680 // Register new endpoint so that packets are routed to it.
681 if err := n.stack.RegisterTransportEndpoint(
682 n.effectiveNetProtos,
683 ProtocolNumber,
684 n.TransportEndpointInfo.ID,
685 n,
686 n.boundPortFlags,
687 n.boundBindToDevice,
688 ); err != nil {
689 n.mu.Unlock()
690 e.acceptMu.Unlock()
691 n.Close()
692
693 e.stack.Stats().TCP.FailedConnectionAttempts.Increment()
694 e.stats.FailedConnectionAttempts.Increment()
695 return err
696 }
697
698 n.isRegistered = true
699 n.TSOffset = n.protocol.tsOffset(s.dstAddr, s.srcAddr)
700
701 // Switch state to connected.
702 n.isConnectNotified = true
703 h := handshake{
704 ep: n,
705 iss: iss,
706 ackNum: irs + 1,
707 rcvWnd: seqnum.Size(n.initialReceiveWindow()),
708 sndWnd: s.window,
709 rcvWndScale: e.rcvWndScaleForHandshake(),
710 sndWndScale: rcvdSynOptions.WS,
711 mss: rcvdSynOptions.MSS,
712 sampleRTTWithTSOnly: true,
713 }
714 h.transitionToStateEstablishedLocked(s)
715
716 // Requeue the segment if the ACK completing the handshake has more info
717 // to be procesed by the newly established endpoint.
718 if (s.flags.Contains(header.TCPFlagFin) || s.data.Size() > 0) && n.enqueueSegment(s) {
719 s.incRef()
720 n.newSegmentWaker.Assert()
721 }
722
723 // Start the protocol goroutine.
724 n.startAcceptedLoop()
725 e.stack.Stats().TCP.PassiveConnectionOpenings.Increment()
726
727 // Deliver the endpoint to the accept queue.
728 e.acceptQueue.endpoints.PushBack(n)
729 e.acceptMu.Unlock()
730
731 e.waiterQueue.Notify(waiter.ReadableEvents)
732 return nil
733
734 default:
735 e.stack.Stats().DroppedPackets.Increment()
736 return nil
737 }
738 }
739
740 // protocolListenLoop is the main loop of a listening TCP endpoint. It runs in
741 // its own goroutine and is responsible for handling connection requests.
742 func (e *endpoint) protocolListenLoop(rcvWnd seqnum.Size) {
743 e.mu.Lock()
744 v6Only := e.ops.GetV6Only()
745 ctx := newListenContext(e.stack, e.protocol, e, rcvWnd, v6Only, e.NetProto)
746
747 defer func() {
748 e.setEndpointState(StateClose)
749
750 // Do cleanup if needed.
751 e.completeWorkerLocked()
752
753 if e.drainDone != nil {
754 close(e.drainDone)
755 }
756 e.mu.Unlock()
757
758 e.drainClosingSegmentQueue()
759
760 // Notify waiters that the endpoint is shutdown.
761 e.waiterQueue.Notify(waiter.ReadableEvents | waiter.WritableEvents | waiter.EventHUp | waiter.EventErr)
762 }()
763
764 var s sleep.Sleeper
765 s.AddWaker(&e.notificationWaker)
766 s.AddWaker(&e.newSegmentWaker)
767 defer s.Done()
768 for {
769 e.mu.Unlock()
770 w := s.Fetch(true)
771 e.mu.Lock()
772 switch w {
773 case &e.notificationWaker:
774 n := e.fetchNotifications()
775 if n&notifyClose != 0 {
776 return
777 }
778 if n&notifyDrain != 0 {
779 for !e.segmentQueue.empty() {
780 s := e.segmentQueue.dequeue()
781 // TODO(gvisor.dev/issue/4690): Better handle errors instead of
782 // silently dropping.
783 _ = e.handleListenSegment(ctx, s)
784 s.decRef()
785 }
786 close(e.drainDone)
787 e.mu.Unlock()
788 <-e.undrain
789 e.mu.Lock()
790 }
791
792 case &e.newSegmentWaker:
793 // Process at most maxSegmentsPerWake segments.
794 mayRequeue := true
795 for i := 0; i < maxSegmentsPerWake; i++ {
796 s := e.segmentQueue.dequeue()
797 if s == nil {
798 mayRequeue = false
799 break
800 }
801
802 // TODO(gvisor.dev/issue/4690): Better handle errors instead of
803 // silently dropping.
804 _ = e.handleListenSegment(ctx, s)
805 s.decRef()
806 }
807
808 // If the queue is not empty, make sure we'll wake up
809 // in the next iteration.
810 if mayRequeue && !e.segmentQueue.empty() {
811 e.newSegmentWaker.Assert()
812 }
813 }
814 }
815 }