]> Cypherpunks.ru repositories - govpn.git/blob - src/cypherpunks.ru/govpn/server/server.go
ef53b8f626e25e79a3ba292dab75f0175808e7e2
[govpn.git] / src / cypherpunks.ru / govpn / server / server.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 server
20
21 import (
22         "sync"
23         "time"
24
25         "github.com/Sirupsen/logrus"
26         "github.com/pkg/errors"
27
28         "cypherpunks.ru/govpn"
29 )
30
31 // PeerConfigurer is used by a GoVPN server to figure the configuration
32 // of a single peer
33 type PeerConfigurer interface {
34         Get(govpn.PeerID) *govpn.PeerConf
35 }
36
37 // MACPeerFinder is used by GoVPN server to figure the PeerID from
38 // handshake data
39 type MACPeerFinder interface {
40         Find([]byte) (*govpn.PeerID, error)
41 }
42
43 // PeerState hold server side state of a single connecting/connected peer
44 type PeerState struct {
45         peer       *govpn.Peer
46         terminator chan struct{}
47         tap        *govpn.TAP
48 }
49
50 // Configuration hold GoVPN server configuration
51 type Configuration struct {
52         BindAddress  string
53         ProxyAddress string
54         Protocol     govpn.Protocol
55         Timeout      time.Duration
56 }
57
58 // Validate return an error if a configuration is invalid
59 func (c *Configuration) Validate() error {
60         if len(c.BindAddress) == 0 {
61                 return errors.New("Missing BindAddress")
62         }
63         return nil
64 }
65
66 // LogFields return a logrus compatible logging context
67 func (c *Configuration) LogFields() logrus.Fields {
68         const prefix = "srv_conf_"
69         f := logrus.Fields{
70                 prefix + "bind":     c.BindAddress,
71                 prefix + "protocol": c.Protocol.String(),
72                 prefix + "timeout":  c.Timeout.String(),
73         }
74         if len(c.ProxyAddress) > 0 {
75                 f[prefix+"proxy"] = c.ProxyAddress
76         }
77         return f
78 }
79
80 // Server is a GoVPN server instance
81 type Server struct {
82         configuration Configuration
83         termSignal    chan interface{}
84
85         idsCache MACPeerFinder
86         confs    PeerConfigurer
87
88         handshakes map[string]*govpn.Handshake
89         hsLock     sync.RWMutex
90
91         peers     map[string]*PeerState
92         peersLock sync.RWMutex
93
94         peersByID     map[govpn.PeerID]string
95         peersByIDLock sync.RWMutex
96
97         knownPeers govpn.KnownPeers
98         kpLock     sync.RWMutex
99
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 (s *Server) LogFields() logrus.Fields {
108         const prefix = "srv_"
109         return logrus.Fields{
110                 prefix + "hs":    len(s.handshakes),
111                 prefix + "peers": len(s.peers),
112                 prefix + "known": len(s.knownPeers),
113         }
114 }
115
116 // KnownPeers return GoVPN peers.
117 // used to get client statistics.
118 func (s *Server) KnownPeers() *govpn.KnownPeers {
119         return &s.knownPeers
120 }
121
122 // NewServer return a configured GoVPN server, to listen network
123 // connection MainCycle must be executed
124 func NewServer(serverConf Configuration, peerConfs PeerConfigurer, idsCache MACPeerFinder, logger *logrus.Logger, termSignal chan interface{}) *Server {
125         govpn.SetLogger(logger)
126         return &Server{
127                 configuration: serverConf,
128                 confs:         peerConfs,
129                 termSignal:    termSignal,
130                 idsCache:      idsCache,
131                 handshakes:    make(map[string]*govpn.Handshake),
132                 peers:         make(map[string]*PeerState),
133                 peersByID:     make(map[govpn.PeerID]string),
134                 knownPeers:    govpn.KnownPeers(make(map[string]**govpn.Peer)),
135                 Error:         make(chan error, 1),
136                 logger:        logger,
137         }
138 }
139
140 // MainCycle main loop that handle connecting/connected client
141 func (s *Server) MainCycle() {
142         switch s.configuration.Protocol {
143         case govpn.ProtocolUDP:
144                 s.startUDP()
145         case govpn.ProtocolTCP:
146                 s.startTCP()
147         case govpn.ProtocolALL:
148                 s.startUDP()
149                 s.startTCP()
150         default:
151                 s.Error <- errors.New("Unknown protocol specified")
152                 return
153         }
154
155         if len(s.configuration.ProxyAddress) > 0 {
156                 go s.proxyStart()
157         }
158         fields := logrus.Fields{"func": logFuncPrefix + "Server.MainCycle"}
159
160         s.logger.WithFields(
161                 fields,
162         ).WithFields(
163                 s.LogFields(),
164         ).WithFields(
165                 s.configuration.LogFields(),
166         ).Info("Starting...")
167
168         var needsDeletion bool
169         var err error
170         hsHeartbeat := time.Tick(s.configuration.Timeout)
171         go func() { <-hsHeartbeat }()
172
173 MainCycle:
174         for {
175                 select {
176                 case <-s.termSignal:
177                         s.logger.WithFields(
178                                 fields,
179                         ).WithFields(
180                                 s.LogFields(),
181                         ).WithFields(
182                                 s.configuration.LogFields(),
183                         ).Info("Terminating")
184                         for _, ps := range s.peers {
185                                 if err = s.callDown(ps); err != nil {
186                                         s.logger.WithFields(
187                                                 fields,
188                                         ).WithError(err).WithFields(
189                                                 ps.peer.LogFields(),
190                                         ).Error("Failed to run callDown")
191                                 }
192                                 if err = ps.tap.Close(); err != nil {
193                                         logrus.WithError(err).WithFields(
194                                                 fields,
195                                         ).WithFields(
196                                                 ps.peer.LogFields(),
197                                         ).Error("Couldn't close TAP")
198                                 }
199                         }
200                         // empty value signals that everything is fine
201                         s.Error <- nil
202                         break MainCycle
203                 case <-hsHeartbeat:
204                         logrus.WithFields(fields).Debug("Heartbeat")
205                         now := time.Now()
206                         s.hsLock.Lock()
207                         for addr, hs := range s.handshakes {
208                                 if hs.LastPing.Add(s.configuration.Timeout).Before(now) {
209                                         logrus.WithFields(
210                                                 fields,
211                                         ).WithFields(
212                                                 hs.LogFields(),
213                                         ).Debug("handshake is expired, delete")
214                                         hs.Zero()
215                                         delete(s.handshakes, addr)
216                                 }
217                         }
218                         s.peersLock.Lock()
219                         s.peersByIDLock.Lock()
220                         s.kpLock.Lock()
221                         for addr, ps := range s.peers {
222                                 ps.peer.BusyR.Lock()
223                                 needsDeletion = ps.peer.LastPing.Add(
224                                         s.configuration.Timeout,
225                                 ).Before(now)
226                                 ps.peer.BusyR.Unlock()
227                                 if needsDeletion {
228                                         logrus.WithFields(
229                                                 fields,
230                                         ).WithFields(
231                                                 ps.peer.LogFields(),
232                                         ).Info("Delete peer")
233                                         delete(s.peers, addr)
234                                         delete(s.knownPeers, addr)
235                                         delete(s.peersByID, *ps.peer.ID)
236                                         if err = s.callDown(ps); err != nil {
237                                                 logrus.WithError(err).WithFields(
238                                                         fields,
239                                                 ).WithFields(
240                                                         ps.peer.LogFields(),
241                                                 ).Error("Couldn't execute callDown")
242                                         }
243                                         if err = ps.tap.Close(); err != nil {
244                                                 logrus.WithError(err).WithFields(
245                                                         fields,
246                                                 ).WithFields(
247                                                         ps.peer.LogFields(),
248                                                 ).Error("Couldn't close TAP")
249                                         }
250                                         ps.terminator <- struct{}{}
251                                 }
252                         }
253                         s.hsLock.Unlock()
254                         s.peersLock.Unlock()
255                         s.peersByIDLock.Unlock()
256                         s.kpLock.Unlock()
257                 }
258         }
259 }