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