瀏覽代碼

Add intermediate secure wrapper

tags/0.10
9seconds 7 年之前
父節點
當前提交
607f4f42c4
共有 2 個檔案被更改,包括 78 行新增2 行删除
  1. 9
    2
      client/middle.go
  2. 69
    0
      wrappers/mtproto_intermediate_secure.go

+ 9
- 2
client/middle.go 查看文件

@@ -17,9 +17,16 @@ func MiddleInit(socket net.Conn, connID string, conf *config.Config) (wrappers.W
17 17
 	}
18 18
 	connStream := conn.(wrappers.StreamReadWriteCloser)
19 19
 
20
-	newConn := wrappers.NewMTProtoAbridged(connStream, opts)
21
-	if opts.ConnectionType != mtproto.ConnectionTypeAbridged {
20
+	var newConn wrappers.PacketReadWriteCloser
21
+	switch opts.ConnectionType {
22
+	case mtproto.ConnectionTypeAbridged:
23
+		newConn = wrappers.NewMTProtoAbridged(connStream, opts)
24
+	case mtproto.ConnectionTypeIntermediate:
22 25
 		newConn = wrappers.NewMTProtoIntermediate(connStream, opts)
26
+	case mtproto.ConnectionTypeSecure:
27
+		newConn = wrappers.NewMTProtoIntermediateSecure(connStream, opts)
28
+	default:
29
+		panic("Unknown connection type")
23 30
 	}
24 31
 
25 32
 	opts.ConnectionProto = mtproto.ConnectionProtocolIPv4

+ 69
- 0
wrappers/mtproto_intermediate_secure.go 查看文件

@@ -0,0 +1,69 @@
1
+package wrappers
2
+
3
+import (
4
+	"bytes"
5
+	"encoding/binary"
6
+	"math/rand"
7
+
8
+	"github.com/9seconds/mtg/mtproto"
9
+)
10
+
11
+type MTProtoIntermediateSecure struct {
12
+	MTProtoIntermediate
13
+}
14
+
15
+func (m *MTProtoIntermediateSecure) Read() ([]byte, error) {
16
+	data, err := m.MTProtoIntermediate.Read()
17
+	if err != nil {
18
+		return nil, err
19
+	}
20
+	length := len(data) - (len(data) % 4)
21
+
22
+	return data[:length], nil
23
+}
24
+
25
+func (m *MTProtoIntermediateSecure) Write(p []byte) (int, error) {
26
+	defer func() {
27
+		m.writeCounter++
28
+	}()
29
+
30
+	m.logger.Debugw("Write packet",
31
+		"simple_ack", m.opts.WriteHacks.SimpleAck,
32
+		"quick_ack", m.opts.WriteHacks.QuickAck,
33
+		"counter", m.writeCounter,
34
+	)
35
+
36
+	if m.opts.ReadHacks.SimpleAck {
37
+		return m.conn.Write(p)
38
+	}
39
+
40
+	buf := &bytes.Buffer{}
41
+	paddingLength := rand.Intn(4)
42
+	buf.Grow(4 + len(p) + paddingLength)
43
+
44
+	binary.Write(buf, binary.LittleEndian, uint32(len(p)+paddingLength))
45
+	buf.Write(p)
46
+	buf.Write(make([]byte, paddingLength))
47
+
48
+	m.logger.Debugw("Write packet with padding",
49
+		"simple_ack", m.opts.WriteHacks.SimpleAck,
50
+		"quick_ack", m.opts.WriteHacks.QuickAck,
51
+		"counter", m.writeCounter,
52
+		"padding_length", paddingLength,
53
+		"length", len(p),
54
+	)
55
+
56
+	_, err := m.conn.Write(buf.Bytes())
57
+
58
+	return len(p), err
59
+}
60
+
61
+func NewMTProtoIntermediateSecure(conn StreamReadWriteCloser, opts *mtproto.ConnectionOpts) PacketReadWriteCloser {
62
+	return &MTProtoIntermediateSecure{
63
+		MTProtoIntermediate: MTProtoIntermediate{
64
+			conn:   conn,
65
+			logger: conn.Logger().Named("mtproto-intermediate-secure"),
66
+			opts:   opts,
67
+		},
68
+	}
69
+}

Loading…
取消
儲存