Repository navigation
Expand file tree
/
Copy patherrors.go
More file actions
359 lines (323 loc) · 8.72 KB
/
Copy patherrors.go
File metadata and controls
359 lines (323 loc) · 8.72 KB
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
package tls
import (
cryptotls "crypto/tls"
"errors"
"sync"
"sync/atomic"
"time"
"gnalloy.org/gnalloy/buffer"
"gnalloy.org/gnalloy/channel"
)
var (
ErrNeedInput = errors.New("gnalloy/handler/tls: need more encrypted input")
ErrInvalidConfig = errors.New("gnalloy/handler/tls: invalid config")
ErrPeerCertificateUnavailable = errors.New("gnalloy/handler/tls: peer certificate unavailable")
ErrNativeTLSUnavailable = errors.New("gnalloy/handler/tls: native tls provider unavailable")
ErrInvalidClientHello = errors.New("gnalloy/handler/tls: invalid client hello")
ErrOCSPStapleRequired = errors.New("gnalloy/handler/tls: ocsp staple required")
ErrOCSPValidationFailed = errors.New("gnalloy/handler/tls: ocsp validation failed")
ErrUnknownCipherSuite = errors.New("gnalloy/handler/tls: unknown cipher suite")
ErrInsecureCipherSuite = errors.New("gnalloy/handler/tls: insecure cipher suite")
ErrTLS13CipherSuiteNotConfigurable = errors.New("gnalloy/handler/tls: tls 1.3 cipher suite is not configurable")
)
// drainWaitTimeout 限制同步 drain 等待后台 TLS 协程产物的最长时间。
const drainWaitTimeout = 100 * time.Millisecond
type Mode uint8
const (
ModeClient Mode = iota + 1
ModeServer
)
type Config struct {
TLS *cryptotls.Config
// Provider 创建底层 TLS 引擎;nil 使用 Go 标准库 crypto/tls。
Provider Provider
// CipherSuites 覆盖 TLS 1.0-1.2 密码套件;TLS 1.3 套件由 Go 运行时管理,不能写入 crypto/tls.Config。
CipherSuites []uint16
// StartTLS 表示连接建立后先透传明文,收到 StartEvent 后再启动 TLS 握手。
StartTLS bool
// VerifyPeerName 在握手完成后对对端证书执行主机名校验,空值表示不额外校验。
VerifyPeerName string
// OCSP 控制 stapled OCSP 响应的强制要求、校验和事件发射。
OCSP OCSPConfig
// BytePool 复用 TLS 中转切片;nil 时使用默认池化实现。
BytePool BytePool
}
type HandshakeEvent struct {
ServerName string
NegotiatedProtocol string
DidResume bool
CipherSuite uint16
Version uint16
}
// StartEvent 触发 StartTLS 模式下的 TLS 握手。
type StartEvent struct{}
type Handler struct {
mode Mode
cfg Config
raw *memoryConn
conn Conn
startOnce sync.Once
closeOnce sync.Once
closed chan struct{}
events chan any
errs chan error
notify chan struct{}
bytePool BytePool
pendingApplication applicationQueue
ctx atomic.Pointer[channel.HandlerContext]
draining atomic.Int32
scheduled atomic.Bool
activated atomic.Bool
handshakeComplete atomic.Bool
handshake bool
active bool
started atomic.Bool
}
func Client(cfg Config) *Handler {
return newHandler(ModeClient, cfg)
}
func Server(cfg Config) *Handler {
return newHandler(ModeServer, cfg)
}
func newHandler(mode Mode, cfg Config) *Handler {
return &Handler{
mode: mode,
cfg: cfg,
closed: make(chan struct{}),
events: make(chan any, 8),
errs: make(chan error, 8),
notify: make(chan struct{}, 1),
bytePool: normalizeBytePool(cfg.BytePool),
}
}
func (h *Handler) HandlerAdded(ctx *channel.HandlerContext) error {
h.ctx.Store(ctx)
if err := h.validateConfig(); err != nil {
return err
}
if !h.cfg.StartTLS {
h.ensureStarted()
}
return nil
}
func (h *Handler) HandlerRemoved(*channel.HandlerContext) error {
h.ctx.Store(nil)
h.close()
h.releaseCiphertext()
return nil
}
func (h *Handler) ChannelActive(ctx *channel.HandlerContext) {
if h.cfg.StartTLS && !h.started.Load() {
h.active = true
ctx.FireChannelActive()
return
}
h.activated.Store(true)
h.ensureStarted()
h.drain(ctx, drainOptions{flush: true, wait: h.mode == ModeClient, plain: true})
}
func (h *Handler) ChannelRead(ctx *channel.HandlerContext, msg any) {
if h.cfg.StartTLS && !h.started.Load() {
ctx.FireChannelRead(msg)
return
}
buf, ok := msg.(buffer.ByteBuf)
if !ok {
if h.handshake {
ctx.FireChannelRead(msg)
return
}
release(msg)
return
}
h.ensureStarted()
err := h.raw.feedBuffer(buf)
if err != nil {
h.fail(ctx, err)
return
}
h.drain(ctx, drainOptions{flush: true, wait: true, plain: true})
}
func (h *Handler) ChannelInactive(ctx *channel.HandlerContext) {
h.close()
h.releaseCiphertext()
ctx.FireChannelInactive()
}
func (h *Handler) Write(ctx *channel.HandlerContext, msg any) error {
return h.write(ctx, msg, false)
}
func (h *Handler) WriteAndFlush(ctx *channel.HandlerContext, msg any) error {
return h.write(ctx, msg, true)
}
func (h *Handler) write(ctx *channel.HandlerContext, msg any, flush bool) error {
if h.cfg.StartTLS && !h.started.Load() {
if flush {
return ctx.WriteAndFlush(msg)
}
return ctx.Write(msg)
}
buf, ok := msg.(buffer.ByteBuf)
if !ok {
if flush {
return ctx.WriteAndFlush(msg)
}
return ctx.Write(msg)
}
if buf.ReadableBytes() == 0 {
buf.Release()
if flush {
return ctx.Flush()
}
return nil
}
h.ensureStarted()
queued, err := h.pendingApplication.enqueue(buf)
if err != nil {
buf.Release()
return err
}
if queued {
h.drain(ctx, drainOptions{flush: flush, wait: flush})
return nil
}
h.draining.Add(1)
defer h.finishDrain()
if err := h.writeApplication(buf); err != nil {
h.fail(ctx, err)
return err
}
h.drainOwned(ctx, drainOptions{flush: flush})
return nil
}
func (h *Handler) Flush(ctx *channel.HandlerContext) error {
if h.cfg.StartTLS && !h.started.Load() {
return ctx.Flush()
}
h.drain(ctx, drainOptions{wait: true})
return ctx.Flush()
}
func (h *Handler) UserEventTriggered(ctx *channel.HandlerContext, event any) {
if _, ok := event.(StartEvent); ok {
h.activated.Store(true)
h.ensureStarted()
h.drain(ctx, drainOptions{flush: true, wait: h.mode == ModeClient, plain: true})
return
}
ctx.FireUserEventTriggered(event)
}
func (h *Handler) Close(ctx *channel.HandlerContext) error {
h.close()
if !h.started.Load() {
return ctx.Close()
}
h.drain(ctx, drainOptions{flush: true})
h.releaseCiphertext()
return ctx.Close()
}
func (h *Handler) ensureStarted() {
h.startOnce.Do(func() {
h.raw = newMemoryConn(h.bytePool, h.notifyDrain)
cfg, err := h.tlsConfig()
if err != nil {
h.started.Store(true)
h.sendErr(err)
return
}
conn, err := h.newTLSConn(cfg)
if err != nil {
h.started.Store(true)
h.sendErr(err)
return
}
h.conn = conn
h.started.Store(true)
go h.runHandshake()
})
}
func (h *Handler) validateConfig() error {
if h.mode != ModeClient && h.mode != ModeServer {
return ErrInvalidConfig
}
if !nativeProviderMissing(h.cfg.Provider) {
if err := providerEvaluationError(EvaluateProvider(h.cfg.Provider)); err != nil {
return err
}
}
return ValidateConfigurableCipherSuites(h.cfg.CipherSuites)
}
func (h *Handler) tlsConfig() (*cryptotls.Config, error) {
cfg := &cryptotls.Config{}
if h.cfg.TLS != nil {
cfg = h.cfg.TLS.Clone()
}
if err := ConfigureCipherSuites(cfg, h.cfg.CipherSuites); err != nil {
return nil, err
}
return cfg, nil
}
func (h *Handler) newTLSConn(cfg *cryptotls.Config) (Conn, error) {
provider := normalizeProvider(h.cfg.Provider)
if h.mode == ModeServer {
return provider.Server(h.raw, cfg)
}
return provider.Client(h.raw, cfg)
}
func (h *Handler) runHandshake() {
if err := h.conn.Handshake(); err != nil {
h.sendErr(err)
return
}
state := h.conn.ConnectionState()
if h.cfg.VerifyPeerName != "" {
if err := verifyPeerName(state, h.cfg.VerifyPeerName); err != nil {
h.sendErr(err)
return
}
}
ocspEvent, emitOCSPEvent, err := h.cfg.OCSP.evaluate(state)
if err != nil {
h.sendErr(err)
return
}
h.events <- HandshakeEvent{
ServerName: state.ServerName,
NegotiatedProtocol: state.NegotiatedProtocol,
DidResume: state.DidResume,
CipherSuite: state.CipherSuite,
Version: state.Version,
}
if emitOCSPEvent {
h.events <- ocspEvent
}
h.notifyDrain()
}
func verifyPeerName(state cryptotls.ConnectionState, name string) error {
if len(state.PeerCertificates) == 0 {
return ErrPeerCertificateUnavailable
}
return state.PeerCertificates[0].VerifyHostname(name)
}
type drainOptions struct {
flush bool
wait bool
plain bool
}
func (h *Handler) drain(ctx *channel.HandlerContext, opts drainOptions) {
h.draining.Add(1)
defer h.finishDrain()
h.drainOwned(ctx, opts)
}
func (h *Handler) finishDrain() {
if h.draining.Add(-1) == 0 && h.hasQueuedDrain() {
h.scheduleDrain()
}
}
func ownedBufferFromChunk(chunk *byteChunk) buffer.ByteBuf {
if chunk == nil || len(chunk.data) == 0 {
return nil
}
data := chunk.data
pool := chunk.pool
*chunk = byteChunk{}
return buffer.NewOwnedBufferWithReleaser(data, pool)
}