-
Notifications
You must be signed in to change notification settings - Fork 6
/
session_cache.go
88 lines (76 loc) · 2.19 KB
/
session_cache.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
package dtls
import (
"crypto/x509"
"encoding/hex"
"sync"
"time"
)
type sessionCacheEntry struct {
Id []byte `json:"id"`
Identity []byte `json:"identity"`
Expires time.Time `json:"expires"`
PublicKey []byte `json:"publicKey"`
cert *x509.Certificate
CertEncoded []byte `json:"cert"`
EccCurve eccCurve `json:"eccCurve"`
EccKeypair *eccKeypair `json:"eccKeypair"`
MasterSecret []byte `json:"masterSecret"`
}
func (sce *sessionCacheEntry) Marshal() []byte {
//tbd
return nil
}
var sessionCache = map[string]sessionCacheEntry{}
var sessionCacheMux sync.Mutex
var sessionCacheSweepTime time.Time
// set to whatever you want the cache time to live to be
var SessionCacheTtl = time.Hour * 24
// set to the interval to look for expired sessions
var SessionCacheSweepInterval = time.Minute * -5
func SessionCacheSize() int {
sessionCacheMux.Lock()
size := len(sessionCache)
sessionCacheMux.Unlock()
return size
}
func getFromSessionCache(sessionId string) *sessionCacheEntry {
sessionCacheMux.Lock()
sce, found := sessionCache[sessionId]
sessionCacheMux.Unlock()
if !found {
return nil
}
return &sce
}
func saveToSessionCache(s *session) {
now := time.Now()
sessionCacheMux.Lock()
sessionCache[hex.EncodeToString(s.Id)] = sessionCacheEntry{
Identity: s.peerIdentity,
MasterSecret: s.handshake.masterSecret,
PublicKey: s.peerPublicKey,
cert: s.peerCert,
EccCurve: s.handshake.eccCurve,
EccKeypair: s.handshake.eccKeypair,
Expires: now.Add(SessionCacheTtl),
}
sessionCacheMux.Unlock()
//after entries are added, check to see if we need to sweep out old sessions.
if sessionCacheSweepTime.Before(now.Add(SessionCacheSweepInterval)) {
go sessionCacheSweep()
sessionCacheSweepTime = now
}
}
func sessionCacheSweep() {
now := time.Now()
sessionCacheMux.Lock()
for sessionId, sce := range sessionCache {
if sce.Expires.Before(now) {
delete(sessionCache, sessionId)
}
}
sessionCacheMux.Unlock()
}