@@ -4,6 +4,8 @@ package server
44import (
55 "crypto/tls"
66 "errors"
7+ "fmt"
8+ "io/ioutil"
79 "sync"
810 "time"
911
@@ -19,12 +21,15 @@ import (
1921)
2022
2123// Server structure
22- type Server struct {
24+ type Server struct { // nolint: maligned
2325 config * config.Config
2426 logger log.Logger
2527 nbClients uint32
2628 nbClientsSync sync.Mutex
2729 zeroClientEvent chan error
30+ tlsOnce sync.Once
31+ tlsConfig * tls.Config
32+ tlsError error
2833 accesses * fsCache
2934}
3035
@@ -43,7 +48,10 @@ func newFsCache() *fsCache {
4348var ErrTimeout = errors .New ("timeout" )
4449
4550// ErrNotImplemented is returned when we're using something that has not been implemented yet
46- var ErrNotImplemented = errors .New ("not implemented" )
51+ // var ErrNotImplemented = errors.New("not implemented")
52+
53+ // ErrNotEnabled is returned when a feature hasn't been enabled
54+ var ErrNotEnabled = errors .New ("not enabled" )
4755
4856// NewServer creates a server instance
4957func NewServer (config * config.Config , logger log.Logger ) (* Server , error ) {
@@ -202,8 +210,43 @@ type ClientDriver struct {
202210 afero.Fs
203211}
204212
213+ func (s * Server ) loadTLSConfig () (* tls.Config , error ) {
214+ tlsConf := s .config .Content .TLS
215+ if tlsConf == nil || tlsConf .ServerCert == nil {
216+ return nil , ErrNotEnabled
217+ }
218+
219+ serverCert := tlsConf .ServerCert
220+
221+ certBytes , errReadFileCert := ioutil .ReadFile (serverCert .Cert )
222+ if errReadFileCert != nil {
223+ return nil , fmt .Errorf ("could not load cert file: %s: %w" , serverCert .Cert , errReadFileCert )
224+ }
225+
226+ keyBytes , errReadFileKey := ioutil .ReadFile (serverCert .Key )
227+ if errReadFileKey != nil {
228+ return nil , fmt .Errorf ("could not load key file: %s: %w" , serverCert .Cert , errReadFileCert )
229+ }
230+
231+ keypair , errKeyPair := tls .X509KeyPair (certBytes , keyBytes )
232+ if errKeyPair != nil {
233+ return nil , fmt .Errorf ("could not parse key pairs: %w" , errKeyPair )
234+ }
235+
236+ return & tls.Config {
237+ MinVersion : tls .VersionTLS12 ,
238+ Certificates : []tls.Certificate {keypair },
239+ }, nil
240+ }
241+
205242// GetTLSConfig returns a TLS Certificate to use
206243// The certificate could frequently change if we use something like "let's encrypt"
207244func (s * Server ) GetTLSConfig () (* tls.Config , error ) {
208- return nil , ErrNotImplemented
245+ // The function is called every single time a control or transfer connection requires a TLS connection. As such
246+ // it's important to cache it.
247+ s .tlsOnce .Do (func () {
248+ s .tlsConfig , s .tlsError = s .loadTLSConfig ()
249+ })
250+
251+ return s .tlsConfig , s .tlsError
209252}
0 commit comments