-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathwintap.go
73 lines (66 loc) · 2.06 KB
/
wintap.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
69
70
71
72
73
package wintap
import (
"fmt"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/registry"
)
var (
TAP_IOCTL_CONFIG_POINT_TO_POINT = TAP_CONTROL_CODE(5, 0)
TAP_IOCTL_SET_MEDIA_STATUS = TAP_CONTROL_CODE(6, 0)
TAP_IOCTL_CONFIG_TUN = TAP_CONTROL_CODE(10, 0)
)
func CTL_CODE(device_type, function, method, access uint32) uint32 {
return (device_type << 16) | (access << 14) | (function << 2) | method
}
func TAP_CONTROL_CODE(request, method uint32) uint32 {
return CTL_CODE(34, request, method, 0)
}
func GetTapGUID() string {
key, err := registry.OpenKey(registry.LOCAL_MACHINE, `SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}`, registry.READ)
if err != nil {
return ""
}
defer key.Close()
kns, err := key.ReadSubKeyNames(-1)
if err != nil {
return ""
}
for _, k := range kns {
subkey, err := registry.OpenKey(key, k, registry.READ)
if err != nil {
continue
}
cid, _, err := subkey.GetStringValue("ComponentId")
if err != nil {
continue
}
if cid == "tap0901" {
guid, _, err := subkey.GetStringValue("NetCfgInstanceId")
if err != nil {
continue
}
return guid
}
}
return ""
}
func GetTapHandle() (windows.Handle, error) {
guid := GetTapGuid()
if guid == "" {
return 0, fmt.Errorf("Please install TAP-Windows Adapter first!")
}
name, _ := windows.UTF16PtrFromString(fmt.Sprintf(`\\.\Global\%s.tap`, guid))
access := uint32(windows.GENERIC_READ | windows.GENERIC_WRITE)
mode := uint32(windows.FILE_SHARE_READ | windows.FILE_SHARE_WRITE)
return windows.CreateFile(name, access, mode, nil, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_SYSTEM, 0)
}
func InitTap(h windows.Handle) error {
var bytesReturned uint32
cmd := []byte{1, 0, 0, 0}
err := windows.DeviceIoControl(h, TAP_IOCTL_SET_MEDIA_STATUS, &cmd[0], uint32(len(cmd)), nil, 0, &bytesReturned, nil)
if err != nil {
return err
}
cmd = []byte{0x0a, 0x03, 0x00, 0x01, 0x0a, 0x03, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00}
return windows.DeviceIoControl(h, TAP_IOCTL_CONFIG_TUN, &cmd[0], uint32(len(cmd)), nil, 0, &bytesReturned, nil)
}