summaryrefslogtreecommitdiffhomepage
path: root/src/tun_linux.go
blob: db13fb090670e64b41a4e2d5b8403bf71451b8f1 (plain)
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
74
75
76
77
78
79
package main

import (
	"encoding/binary"
	"errors"
	"os"
	"strings"
	"syscall"
	"unsafe"
)

/* Implementation of the TUN device interface for linux
 */

const CloneDevicePath = "/dev/net/tun"

const (
	IFF_NO_PI = 0x1000
	IFF_TUN   = 0x1
	IFNAMSIZ  = 0x10
	TUNSETIFF = 0x400454CA
)

type NativeTun struct {
	fd   *os.File
	name string
	mtu  uint
}

func (tun *NativeTun) Name() string {
	return tun.name
}

func (tun *NativeTun) MTU() uint {
	return tun.mtu
}

func (tun *NativeTun) Write(d []byte) (int, error) {
	return tun.fd.Write(d)
}

func (tun *NativeTun) Read(d []byte) (int, error) {
	return tun.fd.Read(d)
}

func CreateTUN(name string) (TUNDevice, error) {
	// Open clone device
	fd, err := os.OpenFile(CloneDevicePath, os.O_RDWR, 0)
	if err != nil {
		return nil, err
	}

	// Prepare ifreq struct
	var ifr [128]byte
	var flags uint16 = IFF_TUN | IFF_NO_PI
	nameBytes := []byte(name)
	if len(nameBytes) >= IFNAMSIZ {
		return nil, errors.New("Name size too long")
	}
	copy(ifr[:], nameBytes)
	binary.LittleEndian.PutUint16(ifr[16:], flags)

	// Create new device
	_, _, errno := syscall.Syscall(syscall.SYS_IOCTL,
		uintptr(fd.Fd()), uintptr(TUNSETIFF),
		uintptr(unsafe.Pointer(&ifr[0])))
	if errno != 0 {
		return nil, errors.New("Failed to create tun, ioctl call failed")
	}

	// Read name of interface
	newName := string(ifr[:])
	newName = newName[:strings.Index(newName, "\000")]
	return &NativeTun{
		fd:   fd,
		name: newName,
		mtu:  1500, // TODO: FIX
	}, nil
}