github.com/MerlinKodo/gvisor@v0.0.0-20231110090155-957f62ecf90e/pkg/tcpip/link/packetsocket/packetsocket.go (about)

     1  // Copyright 2022 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 endpoint that enables delivery of
    16  // incoming and outgoing packets to any interested packet sockets.
    17  package packetsocket
    18  
    19  import (
    20  	"github.com/MerlinKodo/gvisor/pkg/tcpip"
    21  	"github.com/MerlinKodo/gvisor/pkg/tcpip/link/nested"
    22  	"github.com/MerlinKodo/gvisor/pkg/tcpip/stack"
    23  )
    24  
    25  var _ stack.NetworkDispatcher = (*endpoint)(nil)
    26  var _ stack.LinkEndpoint = (*endpoint)(nil)
    27  
    28  type endpoint struct {
    29  	nested.Endpoint
    30  }
    31  
    32  // New creates a new packetsocket link endpoint wrapping a lower link endpoint.
    33  //
    34  // On ingress, the lower link endpoint must only deliver packets that have
    35  // a link-layer header set if one is required for the link.
    36  func New(lower stack.LinkEndpoint) stack.LinkEndpoint {
    37  	e := &endpoint{}
    38  	e.Endpoint.Init(lower, e)
    39  	return e
    40  }
    41  
    42  // DeliverNetworkPacket implements stack.NetworkDispatcher.
    43  func (e *endpoint) DeliverNetworkPacket(protocol tcpip.NetworkProtocolNumber, pkt stack.PacketBufferPtr) {
    44  	e.Endpoint.DeliverLinkPacket(protocol, pkt)
    45  
    46  	e.Endpoint.DeliverNetworkPacket(protocol, pkt)
    47  }
    48  
    49  // WritePackets implements stack.LinkEndpoint.
    50  func (e *endpoint) WritePackets(pkts stack.PacketBufferList) (int, tcpip.Error) {
    51  	for _, pkt := range pkts.AsSlice() {
    52  		e.Endpoint.DeliverLinkPacket(pkt.NetworkProtocolNumber, pkt)
    53  	}
    54  
    55  	return e.Endpoint.WritePackets(pkts)
    56  }