-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
client.go
77 lines (61 loc) · 2.1 KB
/
client.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
package mtproto
import (
"context"
"v2ray.com/core/common"
"v2ray.com/core/common/buf"
"v2ray.com/core/common/crypto"
"v2ray.com/core/common/net"
"v2ray.com/core/common/session"
"v2ray.com/core/common/task"
"v2ray.com/core/transport"
"v2ray.com/core/transport/internet"
)
type Client struct {
}
func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
return &Client{}, nil
}
func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
outbound := session.OutboundFromContext(ctx)
if outbound == nil || !outbound.Target.IsValid() {
return newError("unknown destination.")
}
dest := outbound.Target
if dest.Network != net.Network_TCP {
return newError("not TCP traffic", dest)
}
conn, err := dialer.Dial(ctx, dest)
if err != nil {
return newError("failed to dial to ", dest).Base(err).AtWarning()
}
defer conn.Close() // nolint: errcheck
sc := SessionContextFromContext(ctx)
auth := NewAuthentication(sc)
defer putAuthenticationObject(auth)
request := func() error {
encryptor := crypto.NewAesCTRStream(auth.EncodingKey[:], auth.EncodingNonce[:])
var header [HeaderSize]byte
encryptor.XORKeyStream(header[:], auth.Header[:])
copy(header[:56], auth.Header[:])
if _, err := conn.Write(header[:]); err != nil {
return newError("failed to write auth header").Base(err)
}
connWriter := buf.NewWriter(crypto.NewCryptionWriter(encryptor, conn))
return buf.Copy(link.Reader, connWriter)
}
response := func() error {
decryptor := crypto.NewAesCTRStream(auth.DecodingKey[:], auth.DecodingNonce[:])
connReader := buf.NewReader(crypto.NewCryptionReader(decryptor, conn))
return buf.Copy(connReader, link.Writer)
}
var responseDoneAndCloseWriter = task.OnSuccess(response, task.Close(link.Writer))
if err := task.Run(ctx, request, responseDoneAndCloseWriter); err != nil {
return newError("connection ends").Base(err)
}
return nil
}
func init() {
common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return NewClient(ctx, config.(*ClientConfig))
}))
}