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