-
-
Notifications
You must be signed in to change notification settings - Fork 128
/
protocol.go
81 lines (67 loc) · 2 KB
/
protocol.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
package transport
import (
"net"
"golang.org/x/xerrors"
"github.com/gotd/td/internal/proto/codec"
)
// Protocol is MTProto transport protocol.
//
// See https://core.telegram.org/mtproto/mtproto-transports
type Protocol struct {
codec func() Codec
}
// NewProtocol creates new transport protocol using user Codec constructor.
//
// See https://core.telegram.org/mtproto/mtproto-transports
func NewProtocol(getCodec func() Codec) Protocol {
return Protocol{
codec: getCodec,
}
}
// Telegram transport protocols.
//
// See https://core.telegram.org/mtproto/mtproto-transports
var (
// Abridged is abridged transport protocol.
//
// See https://core.telegram.org/mtproto/mtproto-transports#abridged
Abridged = NewProtocol(func() Codec { return codec.Abridged{} })
// Intermediate is intermediate transport protocol.
//
// See https://core.telegram.org/mtproto/mtproto-transports#intermediate
Intermediate = NewProtocol(func() Codec { return codec.Intermediate{} })
// PaddedIntermediate is padded intermediate transport protocol.
//
// See https://core.telegram.org/mtproto/mtproto-transports#padded-intermediate
PaddedIntermediate = NewProtocol(func() Codec { return codec.PaddedIntermediate{} })
// Full is full transport protocol.
//
// See https://core.telegram.org/mtproto/mtproto-transports#full
Full = NewProtocol(func() Codec { return &codec.Full{} })
)
// Codec creates new codec using protocol settings.
func (p Protocol) Codec() Codec {
return p.codec()
}
// Handshake inits given net.Conn as MTProto connection.
func (p Protocol) Handshake(conn net.Conn) (Conn, error) {
connCodec := p.codec()
if err := connCodec.WriteHeader(conn); err != nil {
return nil, xerrors.Errorf("write header: %w", err)
}
return &connection{
conn: conn,
codec: connCodec,
}, nil
}
// Pipe creates a in-memory MTProto connection.
func (p Protocol) Pipe() (a, b Conn) {
p1, p2 := net.Pipe()
return &connection{
conn: p1,
codec: p.codec(),
}, &connection{
conn: p2,
codec: p.codec(),
}
}