-
-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathmtproto.go
More file actions
executable file
·1585 lines (1356 loc) · 42.5 KB
/
mtproto.go
File metadata and controls
executable file
·1585 lines (1356 loc) · 42.5 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
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 @AmarnathCJD
package gogram
import (
"context"
"crypto/rsa"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/amarnathcjd/gogram/internal/encoding/tl"
"github.com/amarnathcjd/gogram/internal/mode"
"github.com/amarnathcjd/gogram/internal/mtproto/messages"
"github.com/amarnathcjd/gogram/internal/mtproto/objects"
"github.com/amarnathcjd/gogram/internal/session"
"github.com/amarnathcjd/gogram/internal/transport"
"github.com/amarnathcjd/gogram/internal/utils"
)
const (
defaultMaxReconnectAttempts = 2000
defaultBaseReconnectDelay = 2 * time.Second
defaultPingInterval = 30 * time.Second
defaultPendingAcksThreshold = 10
)
type ReconnectConfig struct {
MaxAttempts int
BaseDelay time.Duration
MaxDelay time.Duration
Timeout time.Duration
}
type ReconnectState struct {
InProgress atomic.Bool
Attempts atomic.Int32
ConsecutiveTimeouts atomic.Int32
ConsecutiveTimeoutStart atomic.Int64
LastSuccessfulConnect atomic.Int64
}
type MTProto struct {
Addr atomic.Value
appID int32
proxy *utils.Proxy
transport transport.Transport
localAddr string
ctxCancel context.CancelFunc
ctxCancelMutex sync.Mutex
routineswg sync.WaitGroup
memorySession bool
tcpState *TcpState
timeOffset atomic.Int64
reqTimeout time.Duration
mode mode.Variant
DcList *utils.DCOptions
transportMu sync.Mutex
authKey []byte
authKeyHash []byte
tempAuthKey []byte
tempAuthKeyHash []byte
tempAuthExpiresAt int64
noRedirect bool
serverSalt atomic.Int64
encrypted atomic.Bool
sessionId atomic.Int64
responseChannels *utils.SyncIntObjectChan
expectedTypes *utils.SyncIntReflectTypes
pendingAcks *utils.SyncSet[int64]
genMsgID func(int64) int64
currentSeqNo atomic.Int32
sessionStorage session.SessionLoader
publicKey *rsa.PublicKey
cdnKeysMu sync.RWMutex
cdnKeys map[int32]*rsa.PublicKey
serviceChannel chan tl.Object
serviceModeActivated bool
authKey404Count atomic.Int64
authKey404Time atomic.Int64
IpV6 bool
Logger *utils.Logger
serverRequestHandlers []func(i any) bool
floodHandler func(err error) bool
errorHandler func(err error) bool
connectionHandler func(err error) error
exported bool
cdn bool
terminated atomic.Bool
senderCounters sync.Map // map[int]int32 - tracks sender count per DC
connConfig ReconnectConfig
connState ReconnectState
useWebSocket bool
useWebSocketTLS bool
enablePFS bool
onMigration func()
messageTracker *utils.SyncIntInt64
messageTypesMap sync.Map // msgID -> request type name
maxRetryDepth int // Maximum retry depth to prevent stack overflow
}
type Config struct {
AuthKeyFile string // Path to auth key file for persistent sessions
AuthAESKey string // AES-256 key for encrypting session file
StringSession string // Base64 encoded session string
SessionStorage session.SessionLoader // Custom session storage implementation
MemorySession bool // Keep session in memory only
AppID int32 // Telegram API ID
EnablePFS bool // Enable Perfect Forward Secrecy
FloodHandler func(err error) bool // Called on FLOOD_WAIT; return true to retry
ErrorHandler func(err error) bool // Called on errors; return true to retry
ConnectionHandler func(err error) error // Custom reconnection handler
ServerHost string // Telegram server address (IP:port)
PublicKey *rsa.PublicKey // RSA public key for server verification
DataCenter int // Data center ID (1-5)
Logger *utils.Logger // Logger instance
Proxy *utils.Proxy // Proxy configuration
Mode string // Transport mode (Abridged, Intermediate, Full)
Ipv6 bool // Prefer IPv6 connections
CustomHost bool // Use custom ServerHost instead of DC lookup
LocalAddr string // Local address to bind (IP:port)
Timeout int // TCP connection timeout (seconds)
ReqTimeout int // RPC request timeout (seconds)
UseWebSocket bool // Use WebSocket transport
UseWebSocketTLS bool // Use secure WebSocket (wss://)
MaxReconnectAttempts int // Max reconnection attempts (default: 2000)
BaseReconnectDelay time.Duration // Initial reconnect delay (default: 2s)
MaxReconnectDelay time.Duration // Maximum reconnect delay (default: 15m)
OnMigration func() // Called after DC migration completes
}
func NewMTProto(c Config) (*MTProto, error) {
if c.SessionStorage == nil {
if c.MemorySession {
c.SessionStorage = session.NewInMemory()
} else {
c.SessionStorage = session.NewFromFile(c.AuthKeyFile, c.AuthAESKey)
}
}
loaded, err := c.SessionStorage.Load()
if err != nil {
if !AnyError(err, session.ErrFileNotExists, session.ErrPathNotFound, session.ErrNotImplementedInJS) {
// if the error is not because of file not found or path not found
if !c.MemorySession {
dir := filepath.Dir(c.AuthKeyFile)
if info, err := os.Stat(dir); err == nil {
if info.IsDir() {
if testFile, err := os.CreateTemp(dir, ".write-test-*"); err != nil {
c.Logger.Warn("no write permission in session directory %s: %v", dir, err)
} else {
testFile.Close()
os.Remove(testFile.Name())
}
} else {
c.Logger.Warn("session directory path is not a directory: %s", dir)
}
}
}
c.Logger.Warn("failed to load session: %v", err)
}
}
if c.Logger == nil {
c.Logger = utils.NewLogger("gogram [mtproto]").SetLevel(utils.InfoLevel)
}
mtproto := &MTProto{
sessionStorage: c.SessionStorage,
serviceChannel: make(chan tl.Object),
publicKey: c.PublicKey,
responseChannels: utils.NewSyncIntObjectChan(),
expectedTypes: utils.NewSyncIntReflectTypes(),
pendingAcks: utils.NewSyncSet[int64](),
genMsgID: utils.NewMsgIDGenerator(),
serverRequestHandlers: make([]func(i any) bool, 0),
Logger: c.Logger,
memorySession: c.MemorySession,
appID: c.AppID,
proxy: c.Proxy,
localAddr: c.LocalAddr,
floodHandler: func(err error) bool { return false },
errorHandler: func(err error) bool { return false },
reqTimeout: utils.MinSafeDuration(c.ReqTimeout),
mode: parseTransportMode(c.Mode),
IpV6: c.Ipv6,
tcpState: NewTcpState(),
DcList: utils.NewDCOptions(),
connConfig: ReconnectConfig{
Timeout: utils.MinSafeDuration(c.Timeout),
MaxDelay: utils.OrDefault(c.MaxReconnectDelay, 15*time.Minute),
MaxAttempts: utils.OrDefault(c.MaxReconnectAttempts, defaultMaxReconnectAttempts),
BaseDelay: utils.OrDefault(c.BaseReconnectDelay, defaultBaseReconnectDelay),
},
useWebSocket: c.UseWebSocket,
useWebSocketTLS: c.UseWebSocketTLS,
enablePFS: c.EnablePFS,
onMigration: c.OnMigration,
messageTracker: utils.NewSyncIntInt64(),
maxRetryDepth: 10,
}
mtproto.SetAddr(c.ServerHost)
mtproto.encrypted.Store(false)
mtproto.sessionId.Store(utils.GenerateSessionID())
mtproto.connState.Attempts.Store(0)
mtproto.Logger.Debug("mtproto sender initialized")
if loaded != nil || c.StringSession != "" {
mtproto.encrypted.Store(true)
}
if err := mtproto.loadAuth(c.StringSession, loaded); err != nil {
return nil, fmt.Errorf("loading auth: %w", err)
}
if c.CustomHost {
mtproto.SetAddr(c.ServerHost)
}
if c.FloodHandler != nil {
mtproto.floodHandler = c.FloodHandler
}
if c.ErrorHandler != nil {
mtproto.errorHandler = c.ErrorHandler
}
if c.ConnectionHandler != nil {
mtproto.connectionHandler = c.ConnectionHandler
}
return mtproto, nil
}
func parseTransportMode(sMode string) mode.Variant {
switch sMode {
case "modeAbridged":
return mode.Abridged
case "modeFull":
return mode.Full
case "modeIntermediate":
return mode.Intermediate
case "modePaddedIntermediate":
return mode.PaddedIntermediate
default:
return mode.Abridged
}
}
func (m *MTProto) LoadSession(sess *session.Session) error {
m.SetAddr(sess.Hostname)
m.authKey = sess.Key
m.authKeyHash = sess.Hash
m.appID = sess.AppID
m.Logger.Debug("loading session from %s", utils.FmtIP(sess.Hostname))
if err := m.SaveSession(m.memorySession); err != nil {
return fmt.Errorf("saving session: %w", err)
}
return nil
}
func (m *MTProto) loadAuth(stringSession string, sess *session.Session) error {
if stringSession != "" {
_, err := m.ImportAuth(stringSession)
if err != nil {
return fmt.Errorf("importing string session: %w", err)
}
} else if sess != nil {
m._loadSession(sess)
}
return nil
}
func (m *MTProto) ExportAuth() (*session.Session, int) {
return &session.Session{
Key: m.authKey,
Hash: m.authKeyHash,
Salt: m.serverSalt.Load(),
Hostname: m.GetAddr(),
AppID: m.AppID(),
}, m.GetDC()
}
func (m *MTProto) ImportRawAuth(authKey, authKeyHash []byte, addr string, appID int32) (bool, error) {
m.SetAddr(addr)
m.authKey = authKey
m.authKeyHash = authKeyHash
m.appID = appID
m.Logger.Debug("importing raw auth credentials")
if err := m.SaveSession(m.memorySession); err != nil {
return false, fmt.Errorf("saving session: %w", err)
}
if err := m.Reconnect(false); err != nil {
return false, fmt.Errorf("reconnecting: %w", err)
}
return true, nil
}
func (m *MTProto) ImportAuth(stringSession string) (bool, error) {
sessionString := session.NewEmptyStringSession()
if err := sessionString.Decode(stringSession); err != nil {
return false, err
}
m.authKey = sessionString.AuthKey
m.authKeyHash = sessionString.AuthKeyHash
m.SetAddr(sessionString.IpAddr)
if m.appID == 0 {
m.appID = sessionString.AppID
}
m.Logger.Debug("importing session from string (%s)", utils.FmtIP(sessionString.IpAddr))
if err := m.SaveSession(m.memorySession); err != nil {
return false, fmt.Errorf("saving session: %w", err)
}
return true, nil
}
func (m *MTProto) GetDC() int {
return m.DcList.SearchAddr(m.GetAddr())
}
func (m *MTProto) SetAddr(addr string) {
m.Addr.Store(addr)
}
func (m *MTProto) GetAddr() string {
return m.Addr.Load().(string)
}
func (m *MTProto) GetTransportType() string {
if m.useWebSocket {
if m.useWebSocketTLS {
return "Wss"
}
return "Ws"
}
if m.proxy != nil && !m.proxy.IsEmpty() {
pType := strings.ToLower(m.proxy.Type)
switch pType {
case "socks4", "socks4a":
return "Socks4"
case "socks5", "socks5h":
return "Socks5"
case "http", "https":
return "Http"
case "mtproxy":
return "Mtproxy"
}
}
if m.IpV6 {
return "Tcp6"
}
return "Tcp"
}
func (m *MTProto) AppID() int32 {
return m.appID
}
func (m *MTProto) SetAppID(appID int32) {
m.appID = appID
}
func (m *MTProto) SetCdnKeys(keys map[int32]*rsa.PublicKey) {
m.cdnKeysMu.Lock()
defer m.cdnKeysMu.Unlock()
m.cdnKeys = keys
}
func (m *MTProto) HasCdnKey(dc int32) (*rsa.PublicKey, bool) {
m.cdnKeysMu.RLock()
defer m.cdnKeysMu.RUnlock()
key, ok := m.cdnKeys[dc]
return key, ok
}
func (m *MTProto) SwitchDc(dc int) error {
if m.noRedirect {
return nil
}
newAddr := m.DcList.GetHostIP(dc, false, m.IpV6)
if newAddr == "" {
return fmt.Errorf("dc %d not found in dc list", dc)
}
m.Logger.Debug("migrating to DC%d", dc)
m.connState.InProgress.Store(true)
defer m.connState.InProgress.Store(false)
if err := m.Disconnect(); err != nil {
return err
}
if err := m.sessionStorage.Delete(); err != nil {
return err
}
m.Logger.Debug("cleared old session for migration")
m.authKey = nil
m.authKeyHash = nil
m.serverSalt.Store(0)
m.encrypted.Store(false)
m.sessionId.Store(utils.GenerateSessionID())
m.tempAuthKey = nil
m.tempAuthKeyHash = nil
m.tempAuthExpiresAt = 0
m.responseChannels = utils.NewSyncIntObjectChan()
m.expectedTypes = utils.NewSyncIntReflectTypes()
m.pendingAcks = utils.NewSyncSet[int64]()
m.currentSeqNo.Store(0)
m.authKey404Count.Store(0)
m.authKey404Time.Store(0)
m.connState.Attempts.Store(0)
m.connState.ConsecutiveTimeouts.Store(0)
m.connState.LastSuccessfulConnect.Store(0)
m.SetAddr(newAddr)
m.Logger.Info("migrated to DC%d (%s)", dc, newAddr)
m.Logger.Debug("establishing connection to DC%d", dc)
errConn := m.CreateConnection(true)
if errConn != nil {
return fmt.Errorf("creating connection: %w", errConn)
}
return nil
}
func (m *MTProto) ExportNewSender(dcID int, mem bool, cdn ...bool) (*MTProto, error) {
newAddr := m.DcList.GetHostIP(dcID, false, m.IpV6)
var senderNum int32
if val, ok := m.senderCounters.Load(dcID); ok {
senderNum = val.(int32) + 1
} else {
senderNum = 1
}
m.senderCounters.Store(dcID, senderNum)
var loggerPrefix string
if len(cdn) > 0 && cdn[0] {
newAddr, _ = m.DcList.GetCDNAddr(dcID)
loggerPrefix = fmt.Sprintf("gogram [cdn>>dc%d#%d]", dcID, senderNum)
} else {
loggerPrefix = fmt.Sprintf("gogram [sender>>dc%d#%d]", dcID, senderNum)
}
logger := utils.NewLogger(loggerPrefix).SetLevel(utils.InfoLevel)
cfg := Config{
DataCenter: dcID,
PublicKey: m.publicKey,
ServerHost: newAddr,
AuthKeyFile: "__exp_" + strconv.Itoa(dcID) + ".dat",
MemorySession: mem,
Logger: logger,
Proxy: m.proxy,
LocalAddr: m.localAddr,
AppID: m.appID,
Ipv6: m.IpV6,
Timeout: int(m.connConfig.Timeout.Seconds()),
ReqTimeout: int(m.reqTimeout.Seconds()),
UseWebSocket: m.useWebSocket,
UseWebSocketTLS: m.useWebSocketTLS,
}
if dcID == m.GetDC() {
cfg.SessionStorage = m.sessionStorage
cfg.StringSession = session.NewStringSession(
m.authKey, m.authKeyHash, dcID, newAddr, m.appID,
).Encode()
}
sender, err := NewMTProto(cfg)
if err != nil {
return nil, fmt.Errorf("creating new MTProto: %w", err)
}
sender.noRedirect = true
sender.exported = true
if len(cdn) > 0 && cdn[0] {
sender.cdn = true
}
if err := sender.CreateConnection(false); err != nil {
sender.Terminate()
return nil, fmt.Errorf("creating connection: %w", err)
}
return sender, nil
}
func (m *MTProto) connectWithRetry(ctx context.Context) error {
err := m.connect(ctx)
if err == nil {
m.connState.Attempts.Store(0)
return nil
}
if m.connectionHandler != nil {
m.Logger.Debug("delegating reconnection to custom handler")
return m.connectionHandler(err)
}
for attempt := range m.connConfig.MaxAttempts {
err := m.connect(ctx)
if err == nil {
if attempt > 0 {
m.Logger.Info("reconnected successfully after %d attempts", attempt+1)
}
m.connState.Attempts.Store(0)
return nil
}
if utils.IsFatalConnectionError(err) {
return err
}
if m.terminated.Load() {
return fmt.Errorf("mtproto terminated during reconnection")
}
delay := min(time.Duration(1<<uint(attempt))*m.connConfig.BaseDelay, m.connConfig.MaxDelay)
m.Logger.Debug("reconnection failed (%d/%d): %v; retrying in %s", attempt+1, m.connConfig.MaxAttempts, err, delay)
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(delay):
continue
}
}
return fmt.Errorf("max reconnection attempts (%d) reached", m.connConfig.MaxAttempts)
}
func (m *MTProto) CreateConnection(withLog bool) error {
if m.terminated.Load() {
return fmt.Errorf("mtproto is terminated, cannot create connection")
}
m.stopRoutines()
m.transportMu.Lock()
if m.transport != nil {
m.transport.Close()
}
m.transport = nil
m.transportMu.Unlock()
ctx, cancelfunc := context.WithCancel(context.Background())
m.ctxCancelMutex.Lock()
m.ctxCancel = cancelfunc
m.ctxCancelMutex.Unlock()
transportType := m.GetTransportType()
if withLog {
m.Logger.Info("connecting to %s (%s)", utils.FmtIP(m.GetAddr()), transportType)
} else {
m.Logger.Debug("connecting to %s (%s)", utils.FmtIP(m.GetAddr()), transportType)
}
err := m.connectWithRetry(ctx)
if err != nil {
m.Logger.WithError(err).Error("failed to create connection")
return err
}
m.tcpState.SetActive(true)
var localAddrLabel string
if m.localAddr != "" {
localAddrLabel = fmt.Sprintf("(-%s)", utils.FmtIP(m.localAddr))
}
var proxyLabel string
if m.proxy != nil && m.proxy.Host != "" {
proxyLabel = fmt.Sprintf("(~%s)", utils.FmtIP(m.proxy.Host))
}
transportType = m.GetTransportType()
logMessage := fmt.Sprintf("connected to %s%s%s (%s)", localAddrLabel, proxyLabel, utils.FmtIP(m.GetAddr()), transportType)
if withLog {
m.Logger.Info(logMessage)
} else {
m.Logger.Debug(logMessage)
}
m.startReadingResponses(ctx)
if !m.exported && !m.cdn {
go m.longPing(ctx)
}
if !m.encrypted.Load() {
m.Logger.Debug("generating new auth key")
err = m.makeAuthKey()
if err != nil {
return err
}
m.Logger.Debug("auth key generated")
}
// Start Perfect Forward Secrecy manager if enabled on the main connection.
if m.enablePFS && !m.exported && !m.cdn {
m.startPFSManager(ctx)
}
return nil
}
func (m *MTProto) connect(ctx context.Context) error {
dcId := m.GetDC()
transportType := "[tcp]"
if m.useWebSocket {
transportType = "[websocket]"
if m.useWebSocketTLS {
transportType = "[websocket (tls)]"
}
}
m.Logger.Debug("init transport %s for DC%d", transportType, dcId)
var err error
cfg := transport.CommonConfig{
Ctx: ctx,
Host: utils.FmtIP(m.GetAddr()),
Timeout: m.connConfig.Timeout,
Socks: m.proxy,
LocalAddr: m.localAddr,
ModeVariant: uint8(m.mode),
DC: dcId,
Logger: m.Logger,
}
var newTransport transport.Transport
if m.useWebSocket {
newTransport, err = transport.NewTransport(m, transport.WSConnConfig{
CommonConfig: cfg,
TLS: m.useWebSocketTLS,
TestMode: false,
}, m.mode)
} else {
newTransport, err = transport.NewTransport(m, transport.TCPConnConfig{
CommonConfig: cfg,
IpV6: m.IpV6,
}, m.mode)
}
if err != nil {
m.Logger.Debug("failed to create %s transport: %v", transportType, err)
return fmt.Errorf("creating transport: %w", err)
}
m.transportMu.Lock()
m.transport = newTransport
m.transportMu.Unlock()
m.Logger.Trace("transport ready")
if err := m.checkRapidReconnect(); err != nil {
return err
}
return nil
}
func (m *MTProto) startPFSManager(ctx context.Context) {
const renewBeforeSeconds int64 = 60 // renew 60s before expiry
const defaultTempLifetimeSeconds int32 = 24 * 60 * 60 // 24h
const retryDelayOnError = 30 * time.Second // backoff on error
const pollNoAuthKeyDelay = 5 * time.Second // wait for authKey
const minSleepSeconds int64 = 5 // minimum wait between checks
m.routineswg.Add(1)
go func() {
defer m.routineswg.Done()
defer m.Logger.Debug("PFS manager stopped")
m.Logger.Debug("PFS manager started")
for {
select {
case <-ctx.Done():
return
default:
}
// require permanent auth key first.
if len(m.authKey) == 0 {
select {
case <-ctx.Done():
return
case <-time.After(pollNoAuthKeyDelay):
}
continue
}
now := time.Now().Unix()
expiresAt := m.tempAuthExpiresAt
needNew := m.tempAuthKey == nil || expiresAt == 0 || now >= expiresAt-renewBeforeSeconds
if needNew {
m.Logger.Debug("generating new temporary auth key for PFS")
if err := m.createTempAuthKey(defaultTempLifetimeSeconds); err != nil {
m.Logger.WithError(err).Error("failed to create temporary auth key")
select {
case <-ctx.Done():
return
case <-time.After(retryDelayOnError):
}
continue
}
if err := m.bindTempAuthKey(); err != nil {
m.Logger.WithError(err).Error("failed to bind temporary auth key")
select {
case <-ctx.Done():
return
case <-time.After(retryDelayOnError):
}
continue
}
// refresh local expiry after successful bind.
expiresAt = m.tempAuthExpiresAt
}
// compute sleep until just before expiry.
if expiresAt == 0 {
// no expiry known (should not normally happen); poll later.
select {
case <-ctx.Done():
return
case <-time.After(pollNoAuthKeyDelay):
}
continue
}
waitSec := max(expiresAt-now-renewBeforeSeconds, minSleepSeconds)
waitDur := time.Duration(waitSec) * time.Second
select {
case <-ctx.Done():
return
case <-time.After(waitDur):
}
}
}()
}
func (m *MTProto) makeRequest(data tl.Object, expectedTypes ...reflect.Type) (any, error) {
ctx, cancel := context.WithTimeout(context.Background(), m.reqTimeout)
defer cancel()
return m.makeRequestCtx(ctx, data, expectedTypes...)
}
func (m *MTProto) makeRequestCtx(ctx context.Context, data tl.Object, expectedTypes ...reflect.Type) (any, error) {
return m.makeRequestCtxWithDepth(ctx, data, 0, expectedTypes...)
}
func (m *MTProto) makeRequestCtxWithDepth(ctx context.Context, data tl.Object, retryDepth int, expectedTypes ...reflect.Type) (any, error) {
if retryDepth >= m.maxRetryDepth {
return nil, fmt.Errorf("maximum retry depth exceeded (%d) - aborting request", m.maxRetryDepth)
}
if err := m.tcpState.WaitForActive(ctx); err != nil {
if m.shouldRetryError(fmt.Errorf("tcp inactive: %w", err)) && retryDepth < m.maxRetryDepth {
m.Logger.Trace("tcp inactive, retrying (depth=%d/%d)", retryDepth+1, m.maxRetryDepth)
retryCtx, cancel := context.WithTimeout(context.Background(), m.reqTimeout)
defer cancel()
return m.makeRequestCtxWithDepth(retryCtx, data, retryDepth+1, expectedTypes...)
}
return nil, fmt.Errorf("tcp inactive: %w", err)
}
respChan, msgID, err := m.sendPacket(data, expectedTypes...)
if err != nil {
if utils.IsTransportError(err) {
m.Logger.WithError(err).Trace("transport error for msgID=%d, reconnecting (depth=%d/%d)", msgID, retryDepth, m.maxRetryDepth)
if reconnErr := m.Reconnect(false); reconnErr != nil {
m.Logger.WithError(reconnErr).Error("reconnect failed after transport error")
return nil, fmt.Errorf("reconnecting after transport error: %w", reconnErr)
}
if retryDepth < m.maxRetryDepth {
return m.makeRequestCtxWithDepth(ctx, data, retryDepth+1, expectedTypes...)
}
return nil, fmt.Errorf("max retries reached after transport error: %w", err)
}
if m.shouldRetryError(err) && retryDepth < m.maxRetryDepth {
m.Logger.Trace("retrying request (depth=%d/%d): %v", retryDepth+1, m.maxRetryDepth, err)
retryCtx, cancel := context.WithTimeout(context.Background(), m.reqTimeout)
defer cancel()
return m.makeRequestCtxWithDepth(retryCtx, data, retryDepth+1, expectedTypes...)
}
return nil, err
}
if msgID != 0 {
m.messageTracker.Add(int(msgID), time.Now().Unix())
m.messageTypesMap.Store(msgID, fmt.Sprintf("%T", data))
m.Logger.Trace("request sent: %T (msgID=%d, d=%d)", data, msgID, retryDepth)
}
select {
case <-ctx.Done():
if msgID != 0 {
_, channelExists := m.responseChannels.Get(int(msgID))
_, expectedExists := m.expectedTypes.Get(int(msgID))
sentTime, trackerExists := m.messageTracker.Get(int(msgID))
m.responseChannels.Delete(int(msgID))
m.expectedTypes.Delete(int(msgID))
m.messageTracker.Delete(int(msgID))
m.messageTypesMap.Delete(msgID)
if channelExists && trackerExists {
waitTime := time.Now().Unix() - sentTime
m.Logger.Debug("request timeout: %T (msgID=%d, retryDepth=%d, waitTime=%ds, err=%v) [channel_exists=true, still_waiting=true]",
data, msgID, retryDepth, waitTime, ctx.Err())
} else {
m.Logger.Debug("request timeout: %T (msgID=%d, retryDepth=%d, err=%v) [channel_exists=%v, expected_exists=%v, tracker_exists=%v - POSSIBLE PREMATURE CLEANUP]",
data, msgID, retryDepth, ctx.Err(), channelExists, expectedExists, trackerExists)
}
}
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
count := m.connState.ConsecutiveTimeouts.Add(1)
if count == 1 {
m.connState.ConsecutiveTimeoutStart.Store(time.Now().Unix())
}
if count >= 5 {
duration := time.Now().Unix() - m.connState.ConsecutiveTimeoutStart.Load()
// If 5 timeouts happen within 60 seconds, it's a rapid failure -> reconnect
// Otherwise, it might be just slow network -> reset counter to avoid "random" reconnects later
if duration < 60 {
m.Logger.Debug("5 consecutive timeouts in %ds (request=%T, tcp_active=%v, retryDepth=%d); reconnecting", duration, data, m.tcpState.GetActive(), retryDepth)
m.connState.ConsecutiveTimeouts.Store(0)
m.tryReconnect()
} else {
m.Logger.Debug("5 consecutive timeouts in %ds (slow accumulation); resetting counter", duration)
m.connState.ConsecutiveTimeouts.Store(0)
}
}
} else {
m.connState.ConsecutiveTimeouts.Store(0)
}
err := fmt.Errorf("request timeout: %w", ctx.Err())
if m.shouldRetryError(err) && retryDepth < m.maxRetryDepth {
m.Logger.Trace("timeout retry (depth=%d/%d)", retryDepth+1, m.maxRetryDepth)
retryCtx, cancel := context.WithTimeout(context.Background(), m.reqTimeout)
defer cancel()
return m.makeRequestCtxWithDepth(retryCtx, data, retryDepth+1, expectedTypes...)
}
return nil, err
case resp := <-respChan:
m.connState.ConsecutiveTimeouts.Store(0)
if msgID != 0 {
sentTime, exists := m.messageTracker.Get(int(msgID))
m.messageTracker.Delete(int(msgID))
if reqType, ok := m.messageTypesMap.LoadAndDelete(msgID); ok {
if exists {
duration := time.Now().Unix() - sentTime
m.Logger.Trace("response received: %s -> %T (msgID=%d, latency=%ds, d=%d)",
reqType, resp, msgID, duration, retryDepth)
} else {
m.Logger.Trace("response received: %s -> %T (msgID=%d, d=%d)",
reqType, resp, msgID, retryDepth)
}
}
}
return m.handleRPCResult(data, resp, expectedTypes...)
}
}
func (m *MTProto) shouldRetryError(err error) bool {
return m.errorHandler != nil && m.errorHandler(err)
}
func (m *MTProto) handleRPCResult(data tl.Object, response tl.Object, expectedTypes ...reflect.Type) (any, error) {
switch r := response.(type) {
case *objects.RpcError:
var rpcError *ErrResponseCode
errors.As(RpcErrorToNative(r, utils.FmtMethod(data)), &rpcError)
// handle dc migration (code 303)
if rpcError.Code == 303 {
if strings.HasPrefix(rpcError.Message, "USER_MIGRATE_") || strings.HasPrefix(rpcError.Message, "PHONE_MIGRATE_") {
if dcIDStr := utils.RegexpDCMigrate.FindStringSubmatch(rpcError.Description); len(dcIDStr) == 2 {
if dcID, err := strconv.Atoi(dcIDStr[1]); err == nil {
if err := m.SwitchDc(dcID); err == nil {
if m.onMigration != nil {
m.onMigration()
}
return nil, &errorDCMigrated{int32(dcID)}
}
}
}
}
return nil, rpcError
}
// handle flood wait errors (code 420)
if strings.Contains(rpcError.Message, "FLOOD_WAIT_") || strings.Contains(rpcError.Message, "FLOOD_PREMIUM_WAIT_") {
if m.floodHandler(rpcError) {
ctx, cancel := context.WithTimeout(context.Background(), m.reqTimeout)
defer cancel()
return m.makeRequestCtx(ctx, data, expectedTypes...)
}
return nil, rpcError
}
m.Logger.Trace("rpc error: code=%d message=%s", rpcError.Code, rpcError.Message)
return nil, rpcError
case *errorSessionConfigsChanged:
if m.exported {
m.Logger.Trace("session config changed, retrying request")
} else {
m.Logger.Debug("session config changed, retrying request")
}
ctx, cancel := context.WithTimeout(context.Background(), m.reqTimeout)
defer cancel()
// Start fresh with depth 0 for session config changes
return m.makeRequestCtxWithDepth(ctx, data, 0, expectedTypes...)
}
return tl.UnwrapNativeTypes(response), nil
}
func (m *MTProto) InvokeRequestWithoutUpdate(data tl.Object, expectedTypes ...reflect.Type) error {
_, _, err := m.sendPacket(data, expectedTypes...)
if err != nil {
return fmt.Errorf("sending packet: %w", err)
}
return err
}
func (m *MTProto) IsTcpActive() bool {
return m.tcpState.GetActive()
}
func (m *MTProto) stopRoutines() {
m.ctxCancelMutex.Lock()
if m.ctxCancel != nil {
m.ctxCancel()
}
m.ctxCancelMutex.Unlock()
m.transportMu.Lock()
tr := m.transport
m.transportMu.Unlock()
if tr != nil {
tr.Close()
}
m.notifyPendingRequestsOfConfigChange()
}
func (m *MTProto) Disconnect() error {
m.tcpState.SetActive(false)