]> Cypherpunks.ru repositories - govpn.git/blob - src/cypherpunks.ru/govpn/client/client.go
Upgrade Client
[govpn.git] / src / cypherpunks.ru / govpn / client / client.go
1 /*
2 GoVPN -- simple secure free software virtual private network daemon
3 Copyright (C) 2014-2017 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 client
20
21 import (
22         "fmt"
23         "time"
24
25         "github.com/Sirupsen/logrus"
26         "github.com/agl/ed25519"
27         "github.com/pkg/errors"
28
29         "cypherpunks.ru/govpn"
30 )
31
32 const logFuncPrefix = "govpn/client."
33
34 // Configuration holds GoVPN client configuration
35 type Configuration struct {
36         PrivateKey          *[ed25519.PrivateKeySize]byte
37         Peer                *govpn.PeerConf
38         Protocol            govpn.Protocol
39         ProxyAddress        string
40         ProxyAuthentication string
41         RemoteAddress       string
42         NoReconnect         bool
43         // FileDescriptor allow to create a Client from a pre-existing file descriptor.
44         // Required for Android. requires TCP protocol
45         FileDescriptor int
46 }
47
48 // Validate returns an error if a configuration is invalid
49 func (c *Configuration) Validate() error {
50         if c.Peer.MTU > govpn.MTUMax {
51                 return errors.Errorf("Invalid MTU %d, maximum allowable is %d", c.Peer.MTU, govpn.MTUMax)
52         }
53         if len(c.RemoteAddress) == 0 {
54                 return errors.New("Missing RemoteAddress")
55         }
56         if len(c.Peer.Iface) == 0 && c.Peer.PreUp == nil {
57                 return errors.New("Missing InterfaceName *or* PreUp")
58         }
59         if c.Protocol != govpn.ProtocolTCP && c.Protocol != govpn.ProtocolUDP {
60                 return errors.Errorf("Invalid protocol %d for client", c.Protocol)
61         }
62         if c.FileDescriptor > 0 && c.Protocol != govpn.ProtocolTCP {
63                 return errors.Errorf("Connect with file descriptor requires protocol %s", govpn.ProtocolTCP.String())
64         }
65         return nil
66 }
67
68 // LogFields return a logrus compatible logging context
69 func (c *Configuration) LogFields() logrus.Fields {
70         const prefix = "client_conf_"
71         f := c.Peer.LogFields(prefix)
72         f[prefix+"protocol"] = c.Protocol.String()
73         f[prefix+"no_reconnect"] = c.NoReconnect
74         if len(c.ProxyAddress) > 0 {
75                 f[prefix+"proxy"] = c.ProxyAddress
76         }
77         if c.FileDescriptor > 0 {
78                 f[prefix+"remote"] = fmt.Sprintf("fd:%d(%s)", c.FileDescriptor, c.RemoteAddress)
79         } else {
80                 f[prefix+"remote"] = c.RemoteAddress
81         }
82         return f
83 }
84
85 func (c *Configuration) isProxy() bool {
86         return len(c.ProxyAddress) > 0
87 }
88
89 // Client is a GoVPN client
90 type Client struct {
91         idsCache      *govpn.MACCache
92         tap           *govpn.TAP
93         knownPeers    govpn.KnownPeers
94         timeouted     chan struct{}
95         rehandshaking chan struct{}
96         termination   chan struct{}
97         firstUpCall   bool
98         termSignal    chan interface{}
99         config        Configuration
100         logger        *logrus.Logger
101
102         // Error channel receives any kind of routine errors
103         Error chan error
104 }
105
106 // LogFields return a logrus compatible logging context
107 func (c *Client) LogFields() logrus.Fields {
108         const prefix = "client_"
109         f := logrus.Fields{
110                 prefix + "remote": c.config.RemoteAddress,
111         }
112         if c.tap != nil {
113                 f[prefix+"interface"] = c.tap.Name
114         }
115         if c.config.Peer != nil {
116                 f[prefix+"id"] = c.config.Peer.ID.String()
117         }
118         return f
119 }
120
121 func (c *Client) postDownAction() error {
122         if c.config.Peer.Down == nil {
123                 return nil
124         }
125         err := c.config.Peer.Down(govpn.PeerContext{
126                 RemoteAddress: c.config.RemoteAddress,
127                 Protocol:      c.config.Protocol,
128                 Config:        *c.config.Peer,
129         })
130         return errors.Wrap(err, "c.config.Peer.Down")
131 }
132
133 func (c *Client) postUpAction() error {
134         if c.config.Peer.Up == nil {
135                 return nil
136         }
137         err := c.config.Peer.Up(govpn.PeerContext{
138                 RemoteAddress: c.config.RemoteAddress,
139                 Protocol:      c.config.Protocol,
140                 Config:        *c.config.Peer,
141         })
142         return errors.Wrap(err, "c.config.Peer.Up")
143 }
144
145 // KnownPeers return GoVPN peers. Always 1.
146 // used to get client statistics.
147 func (c *Client) KnownPeers() *govpn.KnownPeers {
148         return &c.knownPeers
149 }
150
151 // MainCycle main loop of a connecting/connected client
152 func (c *Client) MainCycle() {
153         var err error
154         l := c.logger.WithFields(logrus.Fields{"func": logFuncPrefix + "Client.MainCycle"})
155         l.WithFields(c.LogFields()).WithFields(c.config.LogFields()).Info("Starting...")
156
157         // if available, run PreUp, it might create interface
158         if c.config.Peer.PreUp != nil {
159                 l.Debug("Running PreUp")
160                 if c.tap, err = c.config.Peer.PreUp(govpn.PeerContext{
161                         RemoteAddress: c.config.RemoteAddress,
162                         Protocol:      c.config.Protocol,
163                         Config:        *c.config.Peer,
164                 }); err != nil {
165                         c.Error <- errors.Wrap(err, "c.config.Peer.PreUp")
166                         return
167                 }
168                 l.Debug("PreUp success")
169         } else {
170                 l.Debug("No PreUp to run")
171         }
172
173         // if tap wasn't set by PreUp, listen here
174         if c.tap == nil {
175                 l.WithField("asking", c.config.Peer.Iface).Debug("No interface, try to listen")
176                 c.tap, err = govpn.TAPListen(c.config.Peer.Iface, c.config.Peer.MTU)
177                 if err != nil {
178                         c.Error <- errors.Wrapf(err, "govpn.TAPListen inteface:%s mtu:%d", c.config.Peer.Iface, c.config.Peer.MTU)
179                         return
180                 }
181         }
182         c.config.Peer.Iface = c.tap.Name
183         l.WithFields(c.LogFields()).Debug("Got interface, start main loop")
184
185 MainCycle:
186         for {
187                 c.timeouted = make(chan struct{})
188                 c.rehandshaking = make(chan struct{})
189                 c.termination = make(chan struct{})
190                 switch c.config.Protocol {
191                 case govpn.ProtocolUDP:
192                         l.Debug("Start UDP")
193                         go c.startUDP()
194                 case govpn.ProtocolTCP:
195                         l.Debug("Start TCP")
196                         if c.config.isProxy() {
197                                 go c.proxyTCP()
198                         } else {
199                                 go c.startTCP()
200                         }
201                 }
202                 select {
203                 case <-c.termSignal:
204                         l.WithFields(c.LogFields()).Debug("Finish")
205                         c.termination <- struct{}{}
206                         // empty value signals that everything is fine
207                         c.Error <- nil
208                         break MainCycle
209                 case <-c.timeouted:
210                         if c.config.NoReconnect {
211                                 l.Debug("No reconnect, stop")
212                                 c.Error <- nil
213                                 break MainCycle
214                         }
215                         l.WithField("timeout", c.config.Peer.Timeout.String()).Debug("Sleep")
216                         time.Sleep(c.config.Peer.Timeout)
217                 case <-c.rehandshaking:
218                 }
219                 close(c.timeouted)
220                 close(c.rehandshaking)
221                 close(c.termination)
222         }
223         l.WithFields(c.config.LogFields()).Debug("Run post down action")
224         if err = c.postDownAction(); err != nil {
225                 c.Error <- errors.Wrap(err, "c.postDownAction")
226         }
227 }
228
229 // NewClient returns a configured GoVPN client, to trigger connection
230 // MainCycle must be executed.
231 func NewClient(conf Configuration, logger *logrus.Logger, termSignal chan interface{}) (*Client, error) {
232         client := Client{
233                 idsCache:    govpn.NewMACCache(),
234                 firstUpCall: true,
235                 config:      conf,
236                 termSignal:  termSignal,
237                 Error:       make(chan error, 1),
238                 knownPeers:  govpn.KnownPeers(make(map[string]**govpn.Peer)),
239                 logger:      logger,
240         }
241         govpn.SetLogger(client.logger)
242         confs := map[govpn.PeerID]*govpn.PeerConf{*conf.Peer.ID: conf.Peer}
243         if err := client.idsCache.Update(&confs); err != nil {
244                 return nil, errors.Wrap(err, "client.idsCache.Update")
245         }
246         return &client, nil
247 }