github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/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  	"time"
    19  
    20  	"github.com/SagerNet/gvisor/pkg/tcpip"
    21  	"github.com/SagerNet/gvisor/pkg/tcpip/buffer"
    22  	"github.com/SagerNet/gvisor/pkg/tcpip/stack"
    23  )
    24  
    25  // saveReceivedAt is invoked by stateify.
    26  func (p *packet) saveReceivedAt() int64 {
    27  	return p.receivedAt.UnixNano()
    28  }
    29  
    30  // loadReceivedAt is invoked by stateify.
    31  func (p *packet) loadReceivedAt(nsec int64) {
    32  	p.receivedAt = time.Unix(0, nsec)
    33  }
    34  
    35  // saveData saves packet.data field.
    36  func (p *packet) saveData() buffer.VectorisedView {
    37  	// We cannot save p.data directly as p.data.views may alias to p.views,
    38  	// which is not allowed by state framework (in-struct pointer).
    39  	return p.data.Clone(nil)
    40  }
    41  
    42  // loadData loads packet.data field.
    43  func (p *packet) loadData(data buffer.VectorisedView) {
    44  	// NOTE: We cannot do the p.data = data.Clone(p.views[:]) optimization
    45  	// here because data.views is not guaranteed to be loaded by now. Plus,
    46  	// data.views will be allocated anyway so there really is little point
    47  	// of utilizing p.views for data.views.
    48  	p.data = data
    49  }
    50  
    51  // beforeSave is invoked by stateify.
    52  func (ep *endpoint) beforeSave() {
    53  	ep.freeze()
    54  }
    55  
    56  // afterLoad is invoked by stateify.
    57  func (ep *endpoint) afterLoad() {
    58  	ep.thaw()
    59  	ep.stack = stack.StackFromEnv
    60  	ep.ops.InitHandler(ep, ep.stack, tcpip.GetStackSendBufferLimits, tcpip.GetStackReceiveBufferLimits)
    61  
    62  	// TODO(github.com/SagerNet/173): Once bind is supported, choose the right NIC.
    63  	if err := ep.stack.RegisterPacketEndpoint(0, ep.netProto, ep); err != nil {
    64  		panic(err)
    65  	}
    66  }