-
-
Notifications
You must be signed in to change notification settings - Fork 119
/
read_loop.go
186 lines (164 loc) · 4.35 KB
/
read_loop.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
package telegram
import (
"context"
"errors"
"fmt"
"io"
"net"
"time"
"github.com/gotd/td/internal/crypto"
"go.uber.org/zap"
"golang.org/x/xerrors"
"github.com/gotd/td/bin"
"github.com/gotd/td/internal/mt"
"github.com/gotd/td/internal/proto"
"github.com/gotd/td/tg"
)
func (c *Client) handleSessionCreated(b *bin.Buffer) error {
var ns mt.NewSessionCreated
if err := ns.Decode(b); err != nil {
return xerrors.Errorf("failed to decode: %x", err)
}
c.log.Info("Session created")
return nil
}
func (c *Client) handleUnknown(b *bin.Buffer) error {
// Can't process unknown type.
id, err := b.PeekID()
if err != nil {
return err
}
c.log.With(
zap.String("type_id", fmt.Sprintf("0x%x", id)),
).Warn("Unknown type id")
return nil
}
func (c *Client) handleMessage(b *bin.Buffer) error {
id, err := b.PeekID()
if err != nil {
// Empty body.
return xerrors.Errorf("failed to determine message type: %w", err)
}
typeStr := "unknown"
if s := c.types.Get(id); s != "" {
typeStr = s
}
c.log.With(
zap.String("type_id", fmt.Sprintf("0x%x", id)),
zap.String("type_str", typeStr),
).Debug("HandleMessage")
switch id {
case mt.BadMsgNotificationTypeID, mt.BadServerSaltTypeID:
return c.handleBadMsg(b)
case proto.MessageContainerTypeID:
return c.processBatch(b)
case mt.NewSessionCreatedTypeID:
return c.handleSessionCreated(b)
case proto.ResultTypeID:
return c.handleResult(b)
case mt.PongTypeID:
return c.handlePong(b)
case mt.MsgsAckTypeID:
return c.handleAck(b)
case proto.GZIPTypeID:
return c.handleGZIP(b)
case tg.UpdatesTypeID:
return c.handleUpdates(b)
default:
return c.handleUnknown(b)
}
}
func (c *Client) processBatch(b *bin.Buffer) error {
var container proto.MessageContainer
if err := container.Decode(b); err != nil {
return xerrors.Errorf("failed to decode container: %w", err)
}
for _, msg := range container.Messages {
if err := c.processContainerMessage(msg); err != nil {
return err
}
}
return nil
}
func (c *Client) processContainerMessage(msg proto.Message) error {
b := &bin.Buffer{Buf: msg.Body}
return c.handleMessage(b)
}
func (c *Client) read(ctx context.Context, b *bin.Buffer) error {
b.Reset()
defer func() {
// Reset deadline.
_ = c.conn.SetReadDeadline(time.Time{})
}()
if err := c.conn.SetReadDeadline(c.deadline(ctx)); err != nil {
return xerrors.Errorf("failed to set read deadline: %w", err)
}
if err := proto.ReadIntermediate(c.conn, b); err != nil {
return xerrors.Errorf("failed to read intermediate: %w", err)
}
if err := c.checkProtocolError(b); err != nil {
return xerrors.Errorf("protocol error: %w", err)
}
// Decrypting.
encMessage := &crypto.EncryptedMessage{}
if err := encMessage.Decode(b); err != nil {
return xerrors.Errorf("failed to decode encrypted message: %w", err)
}
msg, err := c.decryptData(encMessage)
if err != nil {
return xerrors.Errorf("failed to decrypt: %w", err)
}
// Buffer now contains plaintext message payload.
b.ResetTo(msg.MessageDataWithPadding[:msg.MessageDataLen])
if err := c.handleMessage(b); err != nil {
return xerrors.Errorf("failed to handle message: %w", err)
}
return nil
}
func (c *Client) readLoop(ctx context.Context) {
b := new(bin.Buffer)
log := c.log.Named("read")
log.Debug("Read loop started")
c.wg.Add(1)
defer c.wg.Done()
for {
err := c.read(ctx, b)
if err == nil {
// Reading ok.
continue
}
if errors.Is(err, io.EOF) {
// Nothing was received.
// TODO(ernado): also check ctx done
if err := c.reconnect(); err != nil {
c.log.With(zap.Error(err)).Error("Failed to reconnect")
}
continue
}
// Checking for read timeout.
var syscall *net.OpError
if errors.As(err, &syscall) && syscall.Timeout() {
// We call SetReadDeadline so such error is expected.
c.log.Debug("No updates")
continue
}
var protoErr *ProtocolErr
if errors.As(err, &protoErr) && protoErr.Code == proto.CodeAuthKeyNotFound {
c.log.Warn("Re-generating keys (server not found key that we provided)")
if err := c.createAuthKey(ctx); err != nil {
// Probably fatal error.
c.log.With(zap.Error(err)).Error("Unable to create auth key")
}
c.log.Info("Created auth keys")
continue
}
select {
case <-ctx.Done():
c.log.Debug("Read loop done (closing)")
return
default:
// Notifying about possible errors.
log.With(zap.Error(err)).Error("Read returned error")
}
}
}