]> Cypherpunks.ru repositories - govpn.git/blob - src/govpn/cmd/govpn-server/udp.go
Ability to use TCP as a base transport
[govpn.git] / src / govpn / cmd / govpn-server / udp.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 main
20
21 import (
22         "log"
23         "net"
24         "time"
25
26         "govpn"
27 )
28
29 type UDPSender struct {
30         conn *net.UDPConn
31         addr *net.UDPAddr
32 }
33
34 func (c UDPSender) Write(data []byte) (int, error) {
35         return c.conn.WriteToUDP(data, c.addr)
36 }
37
38 func startUDP() chan Pkt {
39         bind, err := net.ResolveUDPAddr("udp", *bindAddr)
40         ready := make(chan struct{})
41         if err != nil {
42                 log.Fatalln("Can not resolve bind address:", err)
43         }
44         lconn, err := net.ListenUDP("udp", bind)
45         if err != nil {
46                 log.Fatalln("Can not listen on UDP:", err)
47         }
48         sink := make(chan Pkt)
49         go func() {
50                 buf := make([]byte, govpn.MTU)
51                 var n int
52                 var raddr *net.UDPAddr
53                 var err error
54                 for {
55                         <-ready
56                         lconn.SetReadDeadline(time.Now().Add(time.Second))
57                         n, raddr, err = lconn.ReadFromUDP(buf)
58                         if err != nil {
59                                 sink <- Pkt{ready: ready}
60                                 continue
61                         }
62                         sink <- Pkt{
63                                 raddr.String(),
64                                 UDPSender{lconn, raddr},
65                                 buf[:n],
66                                 ready,
67                         }
68                 }
69         }()
70         ready <- struct{}{}
71         return sink
72 }