]> Cypherpunks.ru repositories - govpn.git/blob - src/govpn/cmd/govpn-client/main.go
d11f84303d9024de86725ded3c1328a92d79540e
[govpn.git] / src / govpn / cmd / govpn-client / main.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 // Simple secure free software virtual private network daemon client.
20 package main
21
22 import (
23         "flag"
24         "log"
25         "net"
26         "os"
27         "os/signal"
28         "time"
29
30         "govpn"
31 )
32
33 var (
34         remoteAddr = flag.String("remote", "", "Remote server address")
35         ifaceName  = flag.String("iface", "tap0", "TAP network interface")
36         IDRaw      = flag.String("id", "", "Client identification")
37         keyPath    = flag.String("key", "", "Path to passphrase file")
38         upPath     = flag.String("up", "", "Path to up-script")
39         downPath   = flag.String("down", "", "Path to down-script")
40         stats      = flag.String("stats", "", "Enable stats retrieving on host:port")
41         mtu        = flag.Int("mtu", 1452, "MTU for outgoing packets")
42         timeoutP   = flag.Int("timeout", 60, "Timeout seconds")
43         noisy      = flag.Bool("noise", false, "Enable noise appending")
44         cpr        = flag.Int("cpr", 0, "Enable constant KiB/sec out traffic rate")
45         egdPath    = flag.String("egd", "", "Optional path to EGD socket")
46 )
47
48 func main() {
49         flag.Parse()
50         timeout := *timeoutP
51         var err error
52         log.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)
53
54         govpn.MTU = *mtu
55
56         id, err := govpn.IDDecode(*IDRaw)
57         if err != nil {
58                 log.Fatalln(err)
59         }
60
61         if *egdPath != "" {
62                 log.Println("Using", *egdPath, "EGD")
63                 govpn.EGDInit(*egdPath)
64         }
65
66         pub, priv := govpn.NewVerifier(id, govpn.StringFromFile(*keyPath))
67         conf := &govpn.PeerConf{
68                 Id:          id,
69                 Timeout:     time.Second * time.Duration(timeout),
70                 NoiseEnable: *noisy,
71                 CPR:         *cpr,
72                 DSAPub:      pub,
73                 DSAPriv:     priv,
74         }
75         govpn.PeersInitDummy(id, conf)
76
77         bind, err := net.ResolveUDPAddr("udp", "0.0.0.0:0")
78         if err != nil {
79                 log.Fatalln("Can not resolve address:", err)
80         }
81         conn, err := net.DialUDP("udp", bind, remote)
82         if err != nil {
83                 log.Fatalln("Can not listen on UDP:", err)
84         }
85         remote, err := net.ResolveUDPAddr("udp", *remoteAddr)
86         if err != nil {
87                 log.Fatalln("Can not resolve remote address:", err)
88         }
89
90         sink := make(chan []byte)
91         ready := make(chan struct{})
92         go func() {
93                 buf := make([]byte, govpn.MTU)
94                 var n int
95                 var err error
96                 for {
97                         <-ready
98                         conn.SetReadDeadline(time.Now().Add(time.Second))
99                         n, err = conn.Read(buf)
100                         if err != nil {
101                                 // This is needed for ticking the timeouts counter outside
102                                 sink <- nil
103                                 continue
104                         }
105                         sink <- buf[:n]
106                 }
107         }()
108         ready <- struct{}{}
109
110         tap, ethSink, ethReady, _, err := govpn.TAPListen(
111                 *ifaceName,
112                 time.Second*time.Duration(timeout),
113                 *cpr,
114         )
115         if err != nil {
116                 log.Fatalln("Can not listen on TAP interface:", err)
117         }
118
119         timeouts := 0
120         firstUpCall := true
121         var peer *govpn.Peer
122         var ethPkt []byte
123         var pkt []byte
124         knownPeers := govpn.KnownPeers(map[string]**govpn.Peer{remote.String(): &peer})
125
126         log.Println(govpn.VersionGet())
127         log.Println("Max MTU on TAP interface:", govpn.TAPMaxMTU())
128         if *stats != "" {
129                 log.Println("Stats are going to listen on", *stats)
130                 statsPort, err := net.Listen("tcp", *stats)
131                 if err != nil {
132                         log.Fatalln("Can not listen on stats port:", err)
133                 }
134                 go govpn.StatsProcessor(statsPort, &knownPeers)
135         }
136
137         termSignal := make(chan os.Signal, 1)
138         signal.Notify(termSignal, os.Interrupt, os.Kill)
139
140         log.Println("Starting handshake")
141         handshake := govpn.HandshakeStart(remote.String(), conn, conf)
142
143 MainCycle:
144         for {
145                 if peer != nil && (peer.BytesIn+peer.BytesOut) > govpn.MaxBytesPerKey {
146                         peer.Zero()
147                         peer = nil
148                         handshake = govpn.HandshakeStart(remote.String(), conn, conf)
149                         log.Println("Rehandshaking")
150                 }
151                 select {
152                 case <-termSignal:
153                         break MainCycle
154                 case ethPkt = <-ethSink:
155                         if peer == nil {
156                                 if len(ethPkt) > 0 {
157                                         ethReady <- struct{}{}
158                                 }
159                                 continue
160                         }
161                         peer.EthProcess(ethPkt, ethReady)
162                 case pkt = <-sink:
163                         timeouts++
164                         if timeouts >= timeout {
165                                 break MainCycle
166                         }
167                         if pkt == nil {
168                                 ready <- struct{}{}
169                                 continue
170                         }
171
172                         if peer == nil {
173                                 if govpn.IDsCache.Find(pkt) == nil {
174                                         log.Println("Invalid identity in handshake packet")
175                                         ready <- struct{}{}
176                                         continue
177                                 }
178                                 if p := handshake.Client(pkt); p != nil {
179                                         log.Println("Handshake completed")
180                                         if firstUpCall {
181                                                 go govpn.ScriptCall(*upPath, *ifaceName)
182                                                 firstUpCall = false
183                                         }
184                                         peer = p
185                                         handshake.Zero()
186                                         handshake = nil
187                                 }
188                                 ready <- struct{}{}
189                                 continue
190                         }
191                         if peer == nil {
192                                 ready <- struct{}{}
193                                 continue
194                         }
195                         if peer.PktProcess(pkt, tap, ready) {
196                                 timeouts = 0
197                         }
198                 }
199         }
200         govpn.ScriptCall(*downPath, *ifaceName)
201 }