github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/pkg/tcpip/link/packetsocket/endpoint.go (about)

     1  // Copyright 2020 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 packetsocket provides a link layer endpoint that provides the ability
    16  // to loop outbound packets to any AF_PACKET sockets that may be interested in
    17  // the outgoing packet.
    18  package packetsocket
    19  
    20  import (
    21  	"github.com/SagerNet/gvisor/pkg/tcpip"
    22  	"github.com/SagerNet/gvisor/pkg/tcpip/link/nested"
    23  	"github.com/SagerNet/gvisor/pkg/tcpip/stack"
    24  )
    25  
    26  type endpoint struct {
    27  	nested.Endpoint
    28  }
    29  
    30  // New creates a new packetsocket LinkEndpoint.
    31  func New(lower stack.LinkEndpoint) stack.LinkEndpoint {
    32  	e := &endpoint{}
    33  	e.Endpoint.Init(lower, e)
    34  	return e
    35  }
    36  
    37  // WritePacket implements stack.LinkEndpoint.WritePacket.
    38  func (e *endpoint) WritePacket(r stack.RouteInfo, protocol tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer) tcpip.Error {
    39  	e.Endpoint.DeliverOutboundPacket(r.RemoteLinkAddress, r.LocalLinkAddress, protocol, pkt)
    40  	return e.Endpoint.WritePacket(r, protocol, pkt)
    41  }
    42  
    43  // WritePackets implements stack.LinkEndpoint.WritePackets.
    44  func (e *endpoint) WritePackets(r stack.RouteInfo, pkts stack.PacketBufferList, proto tcpip.NetworkProtocolNumber) (int, tcpip.Error) {
    45  	for pkt := pkts.Front(); pkt != nil; pkt = pkt.Next() {
    46  		e.Endpoint.DeliverOutboundPacket(r.RemoteLinkAddress, r.LocalLinkAddress, pkt.NetworkProtocolNumber, pkt)
    47  	}
    48  
    49  	return e.Endpoint.WritePackets(r, pkts, proto)
    50  }