package mtproto
import (
"context"
"io"
"sync"
"time"
"github.com/go-faster/errors"
"github.com/gotd/log"
"go.uber.org/atomic"
"github.com/gotd/td/bin"
"github.com/gotd/td/clock"
"github.com/gotd/td/crypto"
"github.com/gotd/td/exchange"
"github.com/gotd/td/mtproto/salts"
"github.com/gotd/td/proto"
"github.com/gotd/td/rpc"
"github.com/gotd/td/tdsync"
"github.com/gotd/td/tmap"
"github.com/gotd/td/transport"
)
type Handler interface {
OnMessage (b *bin .Buffer ) error
OnSession (session Session ) error
}
type MessageIDSource interface {
New (t proto .MessageType ) int64
}
type MessageBuf interface {
Consume (id int64 ) bool
}
type Cipher interface {
DecryptFromBuffer (k crypto .AuthKey , buf *bin .Buffer ) (*crypto .EncryptedMessageData , error )
Encrypt (key crypto .AuthKey , data crypto .EncryptedMessageData , b *bin .Buffer ) error
}
type Dialer func (ctx context .Context ) (transport .Conn , error )
type Conn struct {
dcID int
dialer Dialer
conn transport .Conn
handler Handler
rpc *rpc .Engine
rsaPublicKeys []exchange .PublicKey
types *tmap .Map
clock clock .Clock
serverTime *ServerTime
rand io .Reader
cipher Cipher
log log .Helper
messageID MessageIDSource
messageIDBuf MessageBuf
sessionMux sync .RWMutex
authKey crypto .AuthKey
permKey crypto .AuthKey
permKeyCreatedAt int64
sessionState *SessionState
pfsBindingLost *tdsync .Ready
permKeyCheck func (ctx context .Context ) (unknown bool , err error )
sessionContinued bool
salt int64
sessionID int64
tempKeyExpiry int64
salts salts .Salts
sentContentMessages int32
reqMux sync .Mutex
sessionStartMsgID atomic .Int64
ackSendChan chan int64
ackBatchSize int
ackInterval time .Duration
ping map [int64 ]chan struct {}
pingMux sync .Mutex
pingTimeout time .Duration
pingInterval time .Duration
gotSession *tdsync .Ready
sessionFailed *tdsync .Ready
exchangeLock sync .RWMutex
compressThreshold int
dialTimeout time .Duration
exchangeTimeout time .Duration
saltFetchInterval time .Duration
getTimeout func (req uint32 ) time .Duration
pfs bool
tempKeyTTL int
ran atomic .Bool
wire WireTracer
wireID int64
}
func New (dialer Dialer , opt Options ) *Conn {
opt .setDefaults ()
conn := &Conn {
dcID : opt .DC ,
dialer : dialer ,
clock : opt .Clock ,
serverTime : opt .ServerTime ,
rand : opt .Random ,
cipher : opt .Cipher ,
log : log .For (opt .Logger ),
messageID : opt .MessageID ,
messageIDBuf : proto .NewMessageIDBuf (100 ),
ackSendChan : make (chan int64 ),
ackInterval : opt .AckInterval ,
ackBatchSize : opt .AckBatchSize ,
rsaPublicKeys : opt .PublicKeys ,
handler : opt .Handler ,
types : opt .Types ,
authKey : opt .Key ,
permKey : opt .PermKey ,
permKeyCreatedAt : opt .KeyCreatedAt ,
sessionState : opt .SessionState ,
salt : opt .Salt ,
ping : map [int64 ]chan struct {}{},
pingTimeout : opt .PingTimeout ,
pingInterval : opt .PingInterval ,
gotSession : tdsync .NewReady (),
sessionFailed : tdsync .NewReady (),
pfsBindingLost : tdsync .NewReady (),
rpc : opt .engine ,
compressThreshold : opt .CompressThreshold ,
dialTimeout : opt .DialTimeout ,
exchangeTimeout : opt .ExchangeTimeout ,
saltFetchInterval : opt .SaltFetchInterval ,
getTimeout : opt .RequestTimeout ,
pfs : opt .EnablePFS ,
tempKeyTTL : opt .TempKeyTTL ,
wire : opt .WireTracer ,
}
if conn .wire != nil {
conn .wireID = wireConnID .Inc ()
}
if conn .pfs {
conn .authKey = crypto .AuthKey {}
if conn .permKey .Zero () && !opt .Key .Zero () {
conn .permKey = opt .Key
}
}
if conn .rpc == nil {
conn .rpc = rpc .New (conn .writeContentMessage , rpc .Options {
Logger : log .Named (opt .Logger , "rpc" ),
RetryInterval : opt .RetryInterval ,
MaxRetries : opt .MaxRetries ,
Clock : opt .Clock ,
DropHandler : conn .dropRPC ,
})
}
return conn
}
func (c *Conn ) handleClose (ctx context .Context ) error {
<-ctx .Done ()
c .log .Debug (ctx , "Closing" )
c .rpc .ForceClose ()
if err := c .conn .Close (); err != nil {
c .log .Debug (ctx , "Failed to cleanup connection" , log .Error (err ))
}
return nil
}
func (c *Conn ) Run (ctx context .Context , f func (ctx context .Context ) error ) (rErr error ) {
if c .ran .Swap (true ) {
return errors .New ("do Run on closed connection" )
}
ctx , cancel := context .WithCancel (ctx )
defer cancel ()
if c .sessionState != nil {
defer c .releaseSessionState ()
}
c .log .Debug (ctx , "Run: start" )
defer c .log .Debug (ctx , "Run: end" )
if c .wire != nil {
defer func () {
c .traceEvent (WireEvent {Type : WireConnDown , Err : rErr })
}()
}
if err := c .connect (ctx ); err != nil {
return errors .Wrap (err , "start" )
}
if c .wire != nil {
s := c .session ()
c .traceKey (WireKeySet , s .Key , c .pfs )
}
{
g := tdsync .NewLogGroup (ctx , c .log .Named ("group" ).Logger ())
g .Go ("handleClose" , c .handleClose )
readStarted := make (chan struct {})
g .Go ("readLoop" , func (ctx context .Context ) error {
close (readStarted )
return c .readLoop (ctx )
})
<-readStarted
if c .pfs {
if err := c .bindTempAuthKey (ctx ); err != nil {
return errors .Wrap (err , "initial temp key bind" )
}
}
if c .sessionContinued {
c .gotSession .Signal ()
if err := c .handler .OnSession (c .session ()); err != nil {
return errors .Wrap (err , "handler.OnSession" )
}
}
g .Go ("pingLoop" , c .pingLoop )
g .Go ("ackLoop" , c .ackLoop )
g .Go ("sessionFailed" , func (ctx context .Context ) error {
select {
case <- c .sessionFailed .Ready ():
return errSessionFailed
case <- ctx .Done ():
return nil
}
})
if c .saltFetchInterval > 0 {
g .Go ("saltsLoop" , c .saltLoop )
}
c .startHTTPWait ()
if c .pfs {
g .Go ("tempKeyRenewal" , c .tempKeyRenewalLoop )
g .Go ("bindingLost" , func (ctx context .Context ) error {
select {
case <- ctx .Done ():
return ctx .Err ()
case <- c .pfsBindingLost .Ready ():
return errors .Wrap (ErrPFSReconnectRequired , "temporary key binding lost" )
}
})
}
g .Go ("userCallback" , f )
if err := g .Wait (); err != nil {
return errors .Wrap (err , "group" )
}
}
return nil
}
The pages are generated with Golds v0.8.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .