-
-
Notifications
You must be signed in to change notification settings - Fork 135
/
transport.go
104 lines (88 loc) · 2.32 KB
/
transport.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package transport
import (
"context"
"net"
"golang.org/x/xerrors"
"github.com/gotd/td/bin"
"github.com/gotd/td/internal/proto/codec"
)
// NewTransport creates transport using user Codec constructor.
func NewTransport(dialer Dialer, getCodec func() Codec) *Transport {
return &Transport{
dialer: orDefaultDialer(dialer),
codec: getCodec,
}
}
// Abridged creates Abridged transport.
//
// See https://core.telegram.org/mtproto/mtproto-transports#abridged
func Abridged(d Dialer) *Transport {
return NewTransport(d, func() Codec {
return codec.Abridged{}
})
}
// Intermediate creates Intermediate transport.
//
// See https://core.telegram.org/mtproto/mtproto-transports#intermediate
func Intermediate(d Dialer) *Transport {
return NewTransport(d, func() Codec {
return codec.Intermediate{}
})
}
// PaddedIntermediate creates Padded intermediate transport.
//
// See https://core.telegram.org/mtproto/mtproto-transports#padded-intermediate
func PaddedIntermediate(d Dialer) *Transport {
return NewTransport(d, func() Codec {
return codec.PaddedIntermediate{}
})
}
// Full creates Full transport.
//
// See https://core.telegram.org/mtproto/mtproto-transports#full
func Full(d Dialer) *Transport {
return NewTransport(d, func() Codec {
return &codec.Full{}
})
}
// Transport is MTProto connection creator.
type Transport struct {
dialer Dialer
codec func() Codec
}
// Codec creates new codec using transport settings.
func (t *Transport) Codec() Codec {
return t.codec()
}
// Conn is transport connection.
type Conn interface {
Send(ctx context.Context, b *bin.Buffer) error
Recv(ctx context.Context, b *bin.Buffer) error
Close() error
}
// DialContext creates new MTProto connection.
func (t *Transport) DialContext(ctx context.Context, network, address string) (Conn, error) {
conn, err := t.dialer.DialContext(ctx, network, address)
if err != nil {
return nil, xerrors.Errorf("dial: %w", err)
}
connCodec := t.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 (t *Transport) Pipe() (a, b Conn) {
p1, p2 := net.Pipe()
return &connection{
conn: p1,
codec: t.codec(),
}, &connection{
conn: p2,
codec: t.codec(),
}
}