Skip to content

Commit

Permalink
Refactor TLS certificate management
Browse files Browse the repository at this point in the history
  • Loading branch information
mrhaoxx committed Jan 5, 2024
1 parent ab1ff65 commit 3f0c9b5
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 45 deletions.
9 changes: 8 additions & 1 deletion tls/api.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
package tls

func (mgr *tlsMgr) GetCerts() {
func (mgr *tlsMgr) GetCerts() []Cert {
mgr.muCerts.RLock()
defer mgr.muCerts.RUnlock()
var certs []Cert
for _, v := range mgr.certs {
certs = append(certs, v)
}
return certs
}
45 changes: 38 additions & 7 deletions tls/certificate.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,66 @@ import (
"crypto/tls"
"crypto/x509"
"strings"
"sync"

utils "github.com/mrhaoxx/OpenNG/utils"
)

// var GlobalCer = []tls.Certificate{}
type certificate struct {
type Cert struct {
*tls.Certificate
dnsnames utils.GroupRegexp
certfile string
}

type tlsMgr struct {
certs map[string]Cert
lookup *utils.BufferedLookup

muCerts sync.RWMutex
}

func NewTlsMgr() *tlsMgr {

var mgr = tlsMgr{
certs: make(map[string]Cert),
}

mgr.lookup = utils.NewBufferedLookup(func(s string) interface{} {
mgr.muCerts.RLock()
defer mgr.muCerts.RUnlock()

for _, v := range mgr.certs {
if v.dnsnames.MatchString(s) {
return v.Certificate
}
}
return nil
})

return &mgr
}

func (m *tlsMgr) getCertificate(dnsname string) *tls.Certificate {
return m.certs[m.lookup.Lookup(dnsname).(string)].Certificate
return m.lookup.Lookup(dnsname).(*tls.Certificate)
}

func (m *tlsMgr) LoadCertificate(certfile, keyfile string) error {
c, e := tls.LoadX509KeyPair(certfile, keyfile)
if e != nil {
return e
} else {
// if watch {
// certwatchlist[certfile] = keyfile
// watcher.Add(certfile)
// }

c.Leaf, _ = x509.ParseCertificate(c.Certificate[0])

m.certs[certfile] = certificate{
m.muCerts.Lock()
m.certs[certfile] = Cert{
Certificate: &c,
dnsnames: utils.MustCompileRegexp(Dnsname2Regexp(c.Leaf.DNSNames)),
certfile: certfile,
}
m.muCerts.Unlock()

return nil
}
}
Expand Down
35 changes: 0 additions & 35 deletions tls/mgr.go

This file was deleted.

2 changes: 0 additions & 2 deletions udp/controller.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
package udp

type udpMgr struct {

}

0 comments on commit 3f0c9b5

Please sign in to comment.