-
-
Notifications
You must be signed in to change notification settings - Fork 135
/
mtproxy.go
90 lines (74 loc) · 1.95 KB
/
mtproxy.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
package transport
import (
"context"
"crypto/rand"
"io"
"net"
"golang.org/x/xerrors"
"github.com/gotd/td/internal/mtproxy"
"github.com/gotd/td/internal/mtproxy/obfuscator"
"github.com/gotd/td/internal/proto/codec"
)
type mtProxyDialer struct {
addr string
original Dialer
rand io.Reader
secret mtproxy.Secret
codec Codec
tag [4]byte
}
func (m mtProxyDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
return m.dial(ctx, network, address, 2)
}
func (m mtProxyDialer) DialTelegram(ctx context.Context, network string, dc int) (Conn, error) {
conn, err := m.dial(ctx, network, m.addr, dc)
if err != nil {
return nil, err
}
return &connection{
conn: conn,
codec: m.codec,
}, nil
}
func (m mtProxyDialer) dial(ctx context.Context, network, address string, dc int) (net.Conn, error) {
c, err := m.original.DialContext(ctx, network, address)
if err != nil {
return nil, err
}
var conn *obfuscator.Conn
switch m.secret.Type {
case mtproxy.Simple, mtproxy.Secured:
conn = obfuscator.Obfuscated2(m.rand, c)
case mtproxy.TLS:
conn = obfuscator.FakeTLS(m.rand, c)
default:
return nil, xerrors.Errorf("unknown MTProxy secret type: %d", m.secret.Type)
}
secret := m.secret
secret.DC = dc
if err := conn.Handshake(m.tag, secret); err != nil {
return nil, xerrors.Errorf("MTProxy handshake: %w", err)
}
return conn, nil
}
// MTProxy creates MTProxy obfuscated transport.
//
// See https://core.telegram.org/mtproto/mtproto-transports#transport-obfuscation.
func MTProxy(d Dialer, addr string, secret []byte) (*Transport, error) {
s, err := mtproxy.ParseSecret(2, secret)
if err != nil {
return nil, err
}
cdc := codec.PaddedIntermediate{}
dialer := mtProxyDialer{
addr: addr,
original: orDefaultDialer(d),
rand: rand.Reader,
secret: s,
codec: cdc,
tag: cdc.ObfuscatedTag(),
}
return NewTransport(dialer, func() Codec {
return codec.NoHeader{Codec: cdc}
}), nil
}