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