github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/pkg/sentry/socket/netlink/provider_vfs2.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 netlink
    16  
    17  import (
    18  	"github.com/SagerNet/gvisor/pkg/abi/linux"
    19  	"github.com/SagerNet/gvisor/pkg/sentry/fsimpl/sockfs"
    20  	"github.com/SagerNet/gvisor/pkg/sentry/kernel"
    21  	"github.com/SagerNet/gvisor/pkg/sentry/vfs"
    22  	"github.com/SagerNet/gvisor/pkg/syserr"
    23  )
    24  
    25  // socketProviderVFS2 implements socket.Provider.
    26  type socketProviderVFS2 struct {
    27  }
    28  
    29  // Socket implements socket.Provider.Socket.
    30  func (*socketProviderVFS2) Socket(t *kernel.Task, stype linux.SockType, protocol int) (*vfs.FileDescription, *syserr.Error) {
    31  	// Netlink sockets must be specified as datagram or raw, but they
    32  	// behave the same regardless of type.
    33  	if stype != linux.SOCK_DGRAM && stype != linux.SOCK_RAW {
    34  		return nil, syserr.ErrSocketNotSupported
    35  	}
    36  
    37  	provider, ok := protocols[protocol]
    38  	if !ok {
    39  		return nil, syserr.ErrProtocolNotSupported
    40  	}
    41  
    42  	p, err := provider(t)
    43  	if err != nil {
    44  		return nil, err
    45  	}
    46  
    47  	s, err := NewVFS2(t, stype, p)
    48  	if err != nil {
    49  		return nil, err
    50  	}
    51  
    52  	vfsfd := &s.vfsfd
    53  	mnt := t.Kernel().SocketMount()
    54  	d := sockfs.NewDentry(t, mnt)
    55  	defer d.DecRef(t)
    56  	if err := vfsfd.Init(s, linux.O_RDWR, mnt, d, &vfs.FileDescriptionOptions{
    57  		DenyPRead:         true,
    58  		DenyPWrite:        true,
    59  		UseDentryMetadata: true,
    60  	}); err != nil {
    61  		return nil, syserr.FromError(err)
    62  	}
    63  	return vfsfd, nil
    64  }
    65  
    66  // Pair implements socket.Provider.Pair by returning an error.
    67  func (*socketProviderVFS2) Pair(*kernel.Task, linux.SockType, int) (*vfs.FileDescription, *vfs.FileDescription, *syserr.Error) {
    68  	// Netlink sockets never supports creating socket pairs.
    69  	return nil, nil, syserr.ErrNotSupported
    70  }