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