Repository navigation
Expand file tree
/
Copy pathloop.go
More file actions
92 lines (75 loc) · 2.1 KB
/
Copy pathloop.go
File metadata and controls
92 lines (75 loc) · 2.1 KB
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
package tgtest
import (
"context"
"github.com/go-faster/errors"
"github.com/gotd/td/bin"
"github.com/gotd/td/exchange"
"github.com/gotd/td/proto/codec"
"github.com/gotd/td/transport"
)
func (s *Server) read(ctx context.Context, conn transport.Conn, b *bin.Buffer) error {
b.Reset()
ctx, cancel := context.WithTimeout(ctx, s.readTimeout)
defer cancel()
if err := conn.Recv(ctx, b); err != nil {
return err
}
return nil
}
func (s *Server) sendProtoError(ctx context.Context, conn transport.Conn, e int32) error {
var buf bin.Buffer
buf.PutInt32(-e)
ctx, cancel := context.WithTimeout(ctx, s.writeTimeout)
defer cancel()
if err := conn.Send(ctx, &buf); err != nil {
return errors.Wrap(err, "send")
}
return nil
}
func (s *Server) serveConn(ctx context.Context, conn transport.Conn) error {
s.log.Debug(ctx, "User connected")
defer func() {
_ = conn.Close()
s.log.Debug(ctx, "User disconnected")
}()
b := new(bin.Buffer)
for {
if err := s.read(ctx, conn, b); err != nil {
return errors.Wrap(err, "read")
}
var authKeyID [8]byte
if err := b.PeekN(authKeyID[:], len(authKeyID)); err != nil {
return errors.Wrap(err, "peek id")
}
// TODO(tdakkota): dispatch by type ID instead?
if _, ok := s.users.getSession(authKeyID); ok {
if err := s.rpcHandle(ctx, conn, b); err != nil {
return errors.Wrap(err, "handle")
}
continue
}
// If authKeyID not found and is not zero, so send protocol error.
if authKeyID != [8]byte{} {
if err := s.sendProtoError(ctx, conn, codec.CodeAuthKeyNotFound); err != nil {
return errors.Wrap(err, "send AuthKeyNotFound")
}
continue
}
s.log.Debug(ctx, "Starting key exchange")
c := newBufferedConn(conn)
c.Push(b)
key, err := s.exchange(ctx, exchangeConn{Conn: c})
if err != nil {
var exchangeErr *exchange.ServerExchangeError
if errors.As(err, &exchangeErr) {
code := exchangeErr.Code
if err := s.sendProtoError(ctx, c, code); err != nil {
return errors.Wrapf(err, "send proto error %v", code)
}
return nil
}
return errors.Wrap(err, "key exchange failed")
}
s.users.addSession(key)
}
}