]> Cypherpunks.ru repositories - govpn.git/blob - src/cypherpunks.ru/govpn/tap.go
Ability to use TUN-interfaces under GNU/Linux
[govpn.git] / src / cypherpunks.ru / govpn / tap.go
1 /*
2 GoVPN -- simple secure free software virtual private network daemon
3 Copyright (C) 2014-2016 Sergey Matveev <stargrave@stargrave.org>
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 package govpn
20
21 import (
22         "io"
23 )
24
25 type TAP struct {
26         Name string
27         Sink chan []byte
28         dev  io.ReadWriter
29 }
30
31 var (
32         taps = make(map[string]*TAP)
33 )
34
35 func NewTAP(ifaceName string, mtu int) (*TAP, error) {
36         tapRaw, err := newTAPer(ifaceName)
37         if err != nil {
38                 return nil, err
39         }
40         tap := TAP{
41                 Name: ifaceName,
42                 dev:  tapRaw,
43                 Sink: make(chan []byte),
44         }
45         go func() {
46                 var n int
47                 var err error
48                 var buf []byte
49                 buf0 := make([]byte, mtu)
50                 buf1 := make([]byte, mtu)
51                 bufZ := false
52                 for {
53                         if bufZ {
54                                 buf = buf0
55                         } else {
56                                 buf = buf1
57                         }
58                         bufZ = !bufZ
59                         n, err = tap.dev.Read(buf)
60                         if err != nil {
61                                 panic("Reading TUN/TAP:" + err.Error())
62                         }
63                         tap.Sink <- buf[:n]
64                 }
65         }()
66         return &tap, nil
67 }
68
69 func (t *TAP) Write(data []byte) (n int, err error) {
70         return t.dev.Write(data)
71 }
72
73 func TAPListen(ifaceName string, mtu int) (*TAP, error) {
74         tap, exists := taps[ifaceName]
75         if exists {
76                 return tap, nil
77         }
78         tap, err := NewTAP(ifaceName, mtu)
79         if err != nil {
80                 return nil, err
81         }
82         taps[ifaceName] = tap
83         return tap, nil
84 }