github.com/nicocha30/gvisor-ligolo@v0.0.0-20230726075806-989fa2c0a413/pkg/sentry/socket/netstack/tun.go (about)

     1  // Copyright 2021 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 netstack
    16  
    17  import (
    18  	"github.com/nicocha30/gvisor-ligolo/pkg/abi/linux"
    19  	"github.com/nicocha30/gvisor-ligolo/pkg/errors/linuxerr"
    20  	"github.com/nicocha30/gvisor-ligolo/pkg/tcpip/link/tun"
    21  )
    22  
    23  // TUNFlagsToLinux converts a tun.Flags to Linux TUN flags.
    24  func TUNFlagsToLinux(flags tun.Flags) uint16 {
    25  	ret := uint16(linux.IFF_NOFILTER)
    26  	if flags.TAP {
    27  		ret |= linux.IFF_TAP
    28  	}
    29  	if flags.TUN {
    30  		ret |= linux.IFF_TUN
    31  	}
    32  	if flags.NoPacketInfo {
    33  		ret |= linux.IFF_NO_PI
    34  	}
    35  	return ret
    36  }
    37  
    38  // LinuxToTUNFlags converts Linux TUN flags to a tun.Flags.
    39  func LinuxToTUNFlags(flags uint16) (tun.Flags, error) {
    40  	// Linux adds IFF_NOFILTER (the same value as IFF_NO_PI unfortunately)
    41  	// when there is no sk_filter. See __tun_chr_ioctl() in
    42  	// net/drivers/tun.c.
    43  	if flags&^uint16(linux.IFF_TUN|linux.IFF_TAP|linux.IFF_NO_PI|linux.IFF_ONE_QUEUE) != 0 {
    44  		return tun.Flags{}, linuxerr.EINVAL
    45  	}
    46  	return tun.Flags{
    47  		TUN:          flags&linux.IFF_TUN != 0,
    48  		TAP:          flags&linux.IFF_TAP != 0,
    49  		NoPacketInfo: flags&linux.IFF_NO_PI != 0,
    50  	}, nil
    51  }