-
Notifications
You must be signed in to change notification settings - Fork 0
/
tls_file_cache.go
176 lines (157 loc) · 4.89 KB
/
tls_file_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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
package chained
import (
"bytes"
"fmt"
"io/ioutil"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/getlantern/errors"
"github.com/getlantern/tlsresumption"
tls "github.com/refraction-networking/utls"
)
type sessionStateForServer struct {
server string
state *tls.ClientSessionState
timestamp time.Time
}
var (
saveSessionStateCh = make(chan sessionStateForServer, 100)
currentSessionStates = make(map[string]sessionStateForServer)
currentSessionStatesMx sync.RWMutex
initOnce sync.Once
)
func persistedSessionStateFor(server string) (*tls.ClientSessionState, time.Time) {
currentSessionStatesMx.RLock()
state, ok := currentSessionStates[server]
currentSessionStatesMx.RUnlock()
if !ok {
return nil, time.Time{}
}
return state.state, state.timestamp
}
func saveSessionState(server string, state *tls.ClientSessionState, updatedTime time.Time) {
if state == nil {
return
}
select {
case saveSessionStateCh <- sessionStateForServer{server, state, updatedTime}:
// okay
default:
// channel full, drop update
}
}
// PersistSessionStates makes sure that session states are stored on disk in the given configDir
func PersistSessionStates(configDir string) {
initOnce.Do(func() {
// We need a write lock here because other go routines can try to access session states
// before this completes.
currentSessionStatesMx.Lock()
persistSessionStates(configDir, 15*time.Second)
currentSessionStatesMx.Unlock()
})
}
func persistSessionStates(configDir string, saveInterval time.Duration) {
filename := filepath.Join(configDir, "tls_session_states")
existing, err := ioutil.ReadFile(filename)
if err == nil {
log.Debugf("Initializing current session states from %v", filename)
rows := strings.Split(string(existing), "\n")
for _, row := range rows {
state, err := parsePersistedState(row)
if err != nil {
log.Errorf("unable to parse persisted session state from %v: %v", filename, err)
continue
}
currentSessionStates[state.server] = *state
}
}
log.Debugf("Will persist client session states at %v", filename)
go maintainSessionStates(filename, saveInterval)
}
func maintainSessionStates(filename string, saveInterval time.Duration) {
dirty := false
saveIfNecessary := func() {
if dirty {
currentSessionStatesMx.RLock()
states := make(map[string]sessionStateForServer, len(currentSessionStates))
for server, state := range currentSessionStates {
states[server] = state
}
currentSessionStatesMx.RUnlock()
serialized := ""
rowDelim := "" // for first row, don't include a delimiter
for server, state := range states {
serializedState, err := tlsresumption.SerializeClientSessionState(state.state)
if err != nil {
log.Errorf("unable to serialize session state for %v: %v", server, err)
continue
}
serialized = fmt.Sprintf(
"%v%v%v,%v,%v",
serialized, rowDelim, server, state.timestamp.Unix(), serializedState)
rowDelim = "\n" // after first row, include a delimiter
}
err := ioutil.WriteFile(filename, []byte(serialized), 0644)
if err != nil {
log.Errorf("unable to update session states in %v: %v", filename, err)
return
}
dirty = false
log.Debugf("updated session states in %v", filename)
}
}
defer saveIfNecessary()
ticker := time.NewTicker(15 * time.Second)
for {
select {
case newState, open := <-saveSessionStateCh:
if !open {
return
}
currentSessionStatesMx.Lock()
// Check to ensure we don't overwrite the same ticket with a new timestamp.
current, ok := currentSessionStates[newState.server]
if !ok || !bytes.Equal(current.state.SessionTicket(), newState.state.SessionTicket()) {
currentSessionStates[newState.server] = newState
}
currentSessionStatesMx.Unlock()
dirty = true
case <-ticker.C:
saveIfNecessary()
}
}
}
func parsePersistedState(row string) (*sessionStateForServer, error) {
// This function decodes both old-form (pre 5.8.5) and new-form (post 5.8.5) rows.
// Old-form rows have the following structure:
// serverName,serializedState
// where serializedState may include commas. New-form rows introduce a timestamp field:
// serverName,timestamp,serializedState
// where timestamp is a Unix epoch second.
state := sessionStateForServer{}
splits := strings.SplitN(row, ",", 2)
if len(splits) != 2 {
return nil, errors.New("expected at least two comma-separated fields")
}
state.server = splits[0]
remainder := splits[1]
// Assume old-form, but try new-form.
serializedState := remainder
splits = strings.SplitN(remainder, ",", 2)
if len(splits) == 2 {
tsUnix, err := strconv.ParseInt(splits[0], 10, 64)
if err == nil {
state.timestamp = time.Unix(tsUnix, 0)
serializedState = splits[1]
}
}
var err error
state.state, err = tlsresumption.ParseClientSessionState(serializedState)
if err != nil {
return nil, errors.New("failed to parse serialized state: %v", err)
}
return &state, nil
}