]> Cypherpunks.ru repositories - govpn.git/blob - tap.go
6b298f713861ec621183dd4f546d00f2fd7afe77
[govpn.git] / tap.go
1 /*
2 GoVPN -- simple secure free software virtual private network daemon
3 Copyright (C) 2014-2015 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         "golang.org/x/crypto/poly1305"
25 )
26
27 type TAP struct {
28         Name   string
29         dev    io.ReadWriter
30         buf    []byte
31         sink   chan []byte
32         ready  chan struct{}
33         synced bool
34 }
35
36 func NewTAP(ifaceName string) (*TAP, error) {
37         maxIfacePktSize := MTU - poly1305.TagSize - NonceSize
38         tapRaw, err := newTAPer(ifaceName)
39         if err != nil {
40                 return nil, err
41         }
42         tap := TAP{
43                 Name:   ifaceName,
44                 dev:    tapRaw,
45                 buf:    make([]byte, maxIfacePktSize),
46                 sink:   make(chan []byte),
47                 ready:  make(chan struct{}),
48                 synced: false,
49         }
50         go func() {
51                 var n int
52                 var err error
53                 for {
54                         <-tap.ready
55                         n, err = tap.dev.Read(tap.buf)
56                         if err != nil {
57                                 panic(err)
58                         }
59                         tap.sink <- tap.buf[:n]
60                 }
61         }()
62         return &tap, nil
63 }
64
65 func (t *TAP) Write(data []byte) (n int, err error) {
66         return t.dev.Write(data)
67 }