forked from lesismal/nbio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tls.go
87 lines (79 loc) · 1.98 KB
/
tls.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
package tls
import (
"github.com/lesismal/llib/std/crypto/tls"
"github.com/soar4/nbio"
"github.com/soar4/nbio/mempool"
)
// Conn .
type Conn = tls.Conn
// Config .
type Config = tls.Config
// Dial returns a net.Conn to be added to a Engine.
func Dial(network, addr string, config *Config) (*tls.Conn, error) {
tlsConn, err := tls.Dial(network, addr, config, mempool.DefaultMemPool)
if err != nil {
return nil, err
}
return tlsConn, nil
}
// WrapOpen returns an opening handler of nbio.Engine.
func WrapOpen(tlsConfig *Config, isClient bool, h func(c *nbio.Conn, tlsConn *Conn)) func(c *nbio.Conn) {
return func(c *nbio.Conn) {
var tlsConn *tls.Conn
sesseion := c.Session()
if sesseion != nil {
tlsConn = sesseion.(*tls.Conn)
}
if tlsConn == nil && !isClient {
tlsConn = tls.NewConn(c, tlsConfig, isClient, true, mempool.DefaultMemPool)
c.SetSession(tlsConn)
}
if h != nil {
h(c, tlsConn)
}
}
}
// WrapClose returns an closing handler of nbio.Engine.
func WrapClose(h func(c *nbio.Conn, tlsConn *Conn, err error)) func(c *nbio.Conn, err error) {
return func(c *nbio.Conn, err error) {
if h != nil && c != nil {
if session := c.Session(); session != nil {
if tlsConn, ok := session.(*Conn); ok {
h(c, tlsConn, err)
}
}
}
}
}
// WrapData returns a data handler of nbio.Engine.
func WrapData(h func(c *nbio.Conn, tlsConn *Conn, data []byte), args ...interface{}) func(c *nbio.Conn, data []byte) {
getBuffer := func() []byte {
return make([]byte, 2048)
}
if len(args) > 0 {
if bh, ok := args[0].(func() []byte); ok {
getBuffer = bh
}
}
return func(c *nbio.Conn, data []byte) {
if session := c.Session(); session != nil {
if tlsConn, ok := session.(*Conn); ok {
tlsConn.Append(data)
buffer := getBuffer()
for {
n, err := tlsConn.Read(buffer)
if err != nil {
c.Close()
return
}
if h != nil && n > 0 {
h(c, tlsConn, buffer[:n])
}
if n == 0 {
return
}
}
}
}
}
}