github.com/sagernet/gvisor@v0.0.0-20240428053021-e691de28565f/pkg/tcpip/transport/packet/endpoint_state.go (about)

     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 packet
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  	"time"
    21  
    22  	"github.com/sagernet/gvisor/pkg/tcpip"
    23  	"github.com/sagernet/gvisor/pkg/tcpip/stack"
    24  )
    25  
    26  // saveReceivedAt is invoked by stateify.
    27  func (p *packet) saveReceivedAt() int64 {
    28  	return p.receivedAt.UnixNano()
    29  }
    30  
    31  // loadReceivedAt is invoked by stateify.
    32  func (p *packet) loadReceivedAt(_ context.Context, nsec int64) {
    33  	p.receivedAt = time.Unix(0, nsec)
    34  }
    35  
    36  // beforeSave is invoked by stateify.
    37  func (ep *endpoint) beforeSave() {
    38  	ep.rcvMu.Lock()
    39  	defer ep.rcvMu.Unlock()
    40  	ep.rcvDisabled = true
    41  	ep.stack.RegisterResumableEndpoint(ep)
    42  }
    43  
    44  // afterLoad is invoked by stateify.
    45  func (ep *endpoint) afterLoad(ctx context.Context) {
    46  	ep.mu.Lock()
    47  	defer ep.mu.Unlock()
    48  
    49  	ep.stack = stack.RestoreStackFromContext(ctx)
    50  	ep.ops.InitHandler(ep, ep.stack, tcpip.GetStackSendBufferLimits, tcpip.GetStackReceiveBufferLimits)
    51  
    52  	if err := ep.stack.RegisterPacketEndpoint(ep.boundNIC, ep.boundNetProto, ep); err != nil {
    53  		panic(fmt.Sprintf("RegisterPacketEndpoint(%d, %d, _): %s", ep.boundNIC, ep.boundNetProto, err))
    54  	}
    55  
    56  	ep.rcvMu.Lock()
    57  	ep.rcvDisabled = false
    58  	ep.rcvMu.Unlock()
    59  }
    60  
    61  // Resume implements tcpip.ResumableEndpoint.Resume.
    62  func (ep *endpoint) Resume() {
    63  	ep.rcvMu.Lock()
    64  	defer ep.rcvMu.Unlock()
    65  	ep.rcvDisabled = false
    66  }