github.com/sagernet/gvisor@v0.0.0-20240428053021-e691de28565f/pkg/tcpip/transport/icmp/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 icmp 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 "github.com/sagernet/gvisor/pkg/tcpip/transport" 25 ) 26 27 // saveReceivedAt is invoked by stateify. 28 func (p *icmpPacket) saveReceivedAt() int64 { 29 return p.receivedAt.UnixNano() 30 } 31 32 // loadReceivedAt is invoked by stateify. 33 func (p *icmpPacket) loadReceivedAt(_ context.Context, nsec int64) { 34 p.receivedAt = time.Unix(0, nsec) 35 } 36 37 // afterLoad is invoked by stateify. 38 func (e *endpoint) afterLoad(ctx context.Context) { 39 stack.RestoreStackFromContext(ctx).RegisterRestoredEndpoint(e) 40 } 41 42 // beforeSave is invoked by stateify. 43 func (e *endpoint) beforeSave() { 44 e.freeze() 45 e.stack.RegisterResumableEndpoint(e) 46 } 47 48 // Restore implements tcpip.RestoredEndpoint.Restore. 49 func (e *endpoint) Restore(s *stack.Stack) { 50 e.thaw() 51 52 e.net.Resume(s) 53 54 e.stack = s 55 e.ops.InitHandler(e, e.stack, tcpip.GetStackSendBufferLimits, tcpip.GetStackReceiveBufferLimits) 56 57 switch state := e.net.State(); state { 58 case transport.DatagramEndpointStateInitial, transport.DatagramEndpointStateClosed: 59 case transport.DatagramEndpointStateBound, transport.DatagramEndpointStateConnected: 60 var err tcpip.Error 61 info := e.net.Info() 62 info.ID.LocalPort = e.ident 63 info.ID, err = e.registerWithStack(info.NetProto, info.ID) 64 if err != nil { 65 panic(fmt.Sprintf("e.registerWithStack(%d, %#v): %s", info.NetProto, info.ID, err)) 66 } 67 e.ident = info.ID.LocalPort 68 default: 69 panic(fmt.Sprintf("unhandled state = %s", state)) 70 } 71 } 72 73 // Resume implements tcpip.ResumableEndpoint.Resume. 74 func (e *endpoint) Resume() { 75 e.thaw() 76 }