Reload TLS certs on SIGHUP

References: https://todo.sr.ht/~emersion/soju/42
This commit is contained in:
Simon Ser 2021-03-18 14:07:03 +01:00
parent 927ee80da1
commit 21e9fe9b3c
2 changed files with 30 additions and 5 deletions

View File

@ -10,6 +10,7 @@ import (
"os" "os"
"os/signal" "os/signal"
"strings" "strings"
"sync/atomic"
"syscall" "syscall"
"github.com/pires/go-proxyproto" "github.com/pires/go-proxyproto"
@ -50,12 +51,19 @@ func main() {
} }
var tlsCfg *tls.Config var tlsCfg *tls.Config
var tlsCert atomic.Value
if cfg.TLS != nil { if cfg.TLS != nil {
cert, err := tls.LoadX509KeyPair(cfg.TLS.CertPath, cfg.TLS.KeyPath) cert, err := tls.LoadX509KeyPair(cfg.TLS.CertPath, cfg.TLS.KeyPath)
if err != nil { if err != nil {
log.Fatalf("failed to load TLS certificate and key: %v", err) log.Fatalf("failed to load TLS certificate and key: %v", err)
} }
tlsCfg = &tls.Config{Certificates: []tls.Certificate{cert}} tlsCert.Store(cert)
tlsCfg = &tls.Config{
GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
return tlsCert.Load().(*tls.Certificate), nil
},
}
} }
srv := soju.NewServer(db) srv := soju.NewServer(db)
@ -180,15 +188,30 @@ func main() {
} }
sigCh := make(chan os.Signal, 1) sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM) signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
if err := srv.Start(); err != nil { if err := srv.Start(); err != nil {
log.Fatal(err) log.Fatal(err)
} }
<-sigCh for sig := range sigCh {
log.Print("shutting down server") switch sig {
srv.Shutdown() case syscall.SIGHUP:
if cfg.TLS != nil {
log.Print("reloading TLS certificate")
cert, err := tls.LoadX509KeyPair(cfg.TLS.CertPath, cfg.TLS.KeyPath)
if err != nil {
log.Printf("failed to reload TLS certificate and key: %v", err)
break
}
tlsCert.Store(cert)
}
case syscall.SIGINT, syscall.SIGTERM:
log.Print("shutting down server")
srv.Shutdown()
return
}
}
} }
func proxyProtoListener(ln net.Listener, srv *soju.Server) net.Listener { func proxyProtoListener(ln net.Listener, srv *soju.Server) net.Listener {

View File

@ -44,6 +44,8 @@ soju supports two connection modes:
For per-client history to work, clients need to indicate their name. This can For per-client history to work, clients need to indicate their name. This can
be done by adding a "@<client>" suffix to the username. be done by adding a "@<client>" suffix to the username.
soju will reload the TLS certificate and key when it receives the HUP signal.
# OPTIONS # OPTIONS
*-h, -help* *-h, -help*