forked from snail007/shadowtunnel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredir_linux.go
68 lines (55 loc) · 1.37 KB
/
redir_linux.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// +build linux
package redir
import (
"errors"
"net"
"strconv"
"syscall"
"unsafe"
)
type sockaddr struct {
family uint16
data [14]byte
}
const SO_ORIGINAL_DST = 80
//realServerAddress returns an intercepted connection's original destination.
func RealServerAddress(conn *net.Conn) (string, error) {
tcpConn, ok := (*conn).(*net.TCPConn)
if !ok {
return "", errors.New("not a TCPConn")
}
file, err := tcpConn.File()
if err != nil {
return "", err
}
// To avoid potential problems from making the socket non-blocking.
tcpConn.Close()
*conn, err = net.FileConn(file)
if err != nil {
return "", err
}
defer file.Close()
fd := file.Fd()
var addr sockaddr
size := uint32(unsafe.Sizeof(addr))
err = getsockopt(int(fd), syscall.SOL_IP, SO_ORIGINAL_DST, uintptr(unsafe.Pointer(&addr)), &size)
if err != nil {
return "", err
}
var ip net.IP
switch addr.family {
case syscall.AF_INET:
ip = addr.data[2:6]
default:
return "", errors.New("unrecognized address family")
}
port := int(addr.data[0])<<8 + int(addr.data[1])
return net.JoinHostPort(ip.String(), strconv.Itoa(port)), nil
}
func getsockopt(s int, level int, name int, val uintptr, vallen *uint32) (err error) {
_, _, e1 := syscall.Syscall6(syscall.SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0)
if e1 != 0 {
err = e1
}
return
}