github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/test/iptables/iptables_unsafe.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 iptables 16 17 import ( 18 "fmt" 19 "unsafe" 20 21 "golang.org/x/sys/unix" 22 ) 23 24 type originalDstError struct { 25 errno unix.Errno 26 } 27 28 func (e originalDstError) Error() string { 29 return fmt.Sprintf("errno (%d) when calling getsockopt(SO_ORIGINAL_DST): %v", int(e.errno), e.errno.Error()) 30 } 31 32 // SO_ORIGINAL_DST gets the original destination of a redirected packet via 33 // getsockopt. 34 const SO_ORIGINAL_DST = 80 35 36 func originalDestination4(connfd int) (unix.RawSockaddrInet4, error) { 37 var addr unix.RawSockaddrInet4 38 var addrLen uint32 = unix.SizeofSockaddrInet4 39 if errno := originalDestination(connfd, unix.SOL_IP, unsafe.Pointer(&addr), &addrLen); errno != 0 { 40 return unix.RawSockaddrInet4{}, originalDstError{errno} 41 } 42 return addr, nil 43 } 44 45 func originalDestination6(connfd int) (unix.RawSockaddrInet6, error) { 46 var addr unix.RawSockaddrInet6 47 var addrLen uint32 = unix.SizeofSockaddrInet6 48 if errno := originalDestination(connfd, unix.SOL_IPV6, unsafe.Pointer(&addr), &addrLen); errno != 0 { 49 return unix.RawSockaddrInet6{}, originalDstError{errno} 50 } 51 return addr, nil 52 } 53 54 func originalDestination(connfd int, level uintptr, optval unsafe.Pointer, optlen *uint32) unix.Errno { 55 _, _, errno := unix.Syscall6( 56 unix.SYS_GETSOCKOPT, 57 uintptr(connfd), 58 level, 59 SO_ORIGINAL_DST, 60 uintptr(optval), 61 uintptr(unsafe.Pointer(optlen)), 62 0) 63 return errno 64 }