-
-
Notifications
You must be signed in to change notification settings - Fork 45
/
mtproto.go
executable file
·868 lines (748 loc) · 22.4 KB
/
mtproto.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
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
// Copyright (c) 2024 RoseLoverX
package gogram
import (
"context"
"crypto/rsa"
"encoding/json"
"fmt"
"io"
"math"
"net/http"
"net/url"
"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"
"github.com/pkg/errors"
)
const (
defaultTimeout = 60 * time.Second // after 60 sec without any read/write, lib will try to reconnect
acksThreshold = 10
)
type MTProto struct {
Addr string
appID int32
proxy *url.URL
transport transport.Transport
ctxCancel context.CancelFunc
routineswg sync.WaitGroup
memorySession bool
tcpActive atomic.Bool
timeOffset int64
mode mode.Variant
authKey []byte
authKeyHash []byte
noRedirect bool
serverSalt int64
encrypted bool
sessionId int64
mutex sync.Mutex
responseChannels *utils.SyncIntObjectChan
expectedTypes *utils.SyncIntReflectTypes
pendingAcks *utils.SyncSet[int64]
genMsgID func(int64) int64
currentSeqNo atomic.Int32
sessionStorage session.SessionLoader
publicKey *rsa.PublicKey
serviceChannel chan tl.Object
serviceModeActivated bool
authKey404 [2]int64
IpV6 bool
sessionBackup *session.Session
Logger *utils.Logger
serverRequestHandlers []func(i any) bool
floodHandler func(err error) bool
errorHandler func(err error)
exported bool
}
type Config struct {
AuthKeyFile string
StringSession string
SessionStorage session.SessionLoader
MemorySession bool
AppID int32
FloodHandler func(err error) bool
ErrorHandler func(err error)
ServerHost string
PublicKey *rsa.PublicKey
DataCenter int
Logger *utils.Logger
Proxy *url.URL
Mode string
Ipv6 bool
CustomHost bool
}
func NewMTProto(c Config) (*MTProto, error) {
if c.SessionStorage == nil {
if c.MemorySession {
c.SessionStorage = session.NewInMemory()
} else {
c.SessionStorage = session.NewFromFile(c.AuthKeyFile)
}
}
loaded, err := c.SessionStorage.Load()
if err != nil {
if !(strings.Contains(err.Error(), session.ErrFileNotExists) || strings.Contains(err.Error(), session.ErrPathNotFound)) {
// if the error is not because of file not found or path not found, return the error
// else, continue with the execution
// check if have write permission in the directory
if _, err := os.OpenFile(filepath.Dir(c.AuthKeyFile), os.O_WRONLY, 0222); err != nil {
return nil, errors.Wrap(err, "check if you have write permission in the directory")
}
return nil, errors.Wrap(err, "loading session")
}
}
if c.Logger == nil {
c.Logger = utils.NewLogger("gogram [mtproto]").SetLevel(utils.InfoLevel)
}
mtproto := &MTProto{
sessionStorage: c.SessionStorage,
Addr: c.ServerHost,
encrypted: false,
sessionId: utils.GenerateSessionID(),
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,
floodHandler: func(err error) bool { return false },
errorHandler: func(err error) {},
mode: parseTransportMode(c.Mode),
IpV6: c.Ipv6,
}
mtproto.Logger.Debug("initializing mtproto...")
mtproto.offsetTime()
if loaded != nil || c.StringSession != "" {
mtproto.encrypted = true
}
if err := mtproto.loadAuth(c.StringSession, loaded); err != nil {
return nil, errors.Wrap(err, "loading auth")
}
if c.CustomHost {
mtproto.Addr = c.ServerHost
}
if c.FloodHandler != nil {
mtproto.floodHandler = c.FloodHandler
}
if c.ErrorHandler != nil {
mtproto.errorHandler = c.ErrorHandler
}
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
default:
return mode.Abridged
}
}
func (m *MTProto) LoadSession(sess *session.Session) error {
m.authKey, m.authKeyHash, m.Addr, m.appID = sess.Key, sess.Hash, sess.Hostname, sess.AppID
m.Logger.Debug("importing auth from session...")
if err := m.SaveSession(m.memorySession); err != nil {
return errors.Wrap(err, "saving session")
}
return nil
}
func (m *MTProto) loadAuth(stringSession string, sess *session.Session) error {
if stringSession != "" {
_, err := m.ImportAuth(stringSession)
if err != nil {
return errors.Wrap(err, "importing string session")
}
} 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,
Hostname: m.Addr,
AppID: m.AppID(),
}, m.GetDC()
}
func (m *MTProto) ImportRawAuth(authKey, authKeyHash []byte, addr string, appID int32) (bool, error) {
m.authKey, m.authKeyHash, m.Addr, m.appID = authKey, authKeyHash, addr, appID
m.Logger.Debug("imported authKey, authKeyHash, addr, appId")
if err := m.SaveSession(m.memorySession); err != nil {
return false, errors.Wrap(err, "saving session")
}
if err := m.Reconnect(false); err != nil {
return false, errors.Wrap(err, "reconnecting")
}
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, m.authKeyHash, m.Addr = sessionString.AuthKey(), sessionString.AuthKeyHash(), sessionString.IpAddr()
if m.appID == 0 {
m.appID = sessionString.AppID()
}
m.Logger.Debug("importing - auth from stringSession...")
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 utils.SearchAddr(m.Addr)
}
func (m *MTProto) AppID() int32 {
return m.appID
}
func (m *MTProto) SetAppID(appID int32) {
m.appID = appID
}
func (m *MTProto) SwitchDc(dc int) (*MTProto, error) {
if m.noRedirect {
return m, nil
}
newAddr := utils.GetHostIp(dc, false, m.IpV6)
if newAddr == "" {
return nil, errors.New("dc_id not found")
}
m.Logger.Debug("migrating to new DC... dc-" + strconv.Itoa(dc))
m.sessionStorage.Delete()
m.Logger.Debug("deleted old auth key file")
cfg := Config{
DataCenter: dc,
PublicKey: m.publicKey,
ServerHost: newAddr,
AuthKeyFile: m.sessionStorage.Path(),
MemorySession: m.memorySession,
Logger: m.Logger,
Proxy: m.proxy,
AppID: m.appID,
Ipv6: m.IpV6,
}
sender, err := NewMTProto(cfg)
if err != nil {
return nil, errors.Wrap(err, "creating new MTProto")
}
sender.serverRequestHandlers = m.serverRequestHandlers
m.stopRoutines()
m.Logger.Info(fmt.Sprintf("user migrated to new dc (%s) - %s", strconv.Itoa(dc), newAddr))
m.Logger.Debug("reconnecting to new dc... dc-" + strconv.Itoa(dc))
errConn := sender.CreateConnection(true)
if errConn != nil {
return nil, errors.Wrap(errConn, "creating connection")
}
return sender, nil
}
func (m *MTProto) ExportNewSender(dcID int, mem bool) (*MTProto, error) {
newAddr := utils.GetHostIp(dcID, false, m.IpV6)
cfg := Config{
DataCenter: dcID,
PublicKey: m.publicKey,
ServerHost: newAddr,
AuthKeyFile: "__exp_" + strconv.Itoa(dcID) + ".dat",
MemorySession: mem,
Logger: m.Logger,
Proxy: m.proxy,
AppID: m.appID,
Ipv6: m.IpV6,
}
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, errors.Wrap(err, "creating new MTProto")
}
sender.noRedirect = true
sender.exported = true
if err := sender.CreateConnection(false); err != nil {
return nil, errors.Wrap(err, "creating connection: exporting")
}
return sender, nil
}
func (m *MTProto) CreateConnection(withLog bool) error {
m.stopRoutines()
ctx, cancelfunc := context.WithCancel(context.Background())
m.ctxCancel = cancelfunc
if withLog {
m.Logger.Info(fmt.Sprintf("connecting to [%s] - <%s> ...", utils.FmtIp(m.Addr), utils.Vtcp(m.IpV6)))
} else {
m.Logger.Debug(fmt.Sprintf("connecting to [%s] - <%s> ...", utils.FmtIp(m.Addr), utils.Vtcp(m.IpV6)))
}
err := m.connect(ctx)
if err != nil {
m.Logger.Error(errors.Wrap(err, "creating connection"))
return err
}
m.tcpActive.Store(true)
if withLog {
if m.proxy != nil && m.proxy.Host != "" {
m.Logger.Info(fmt.Sprintf("connection to (~%s)[%s] - <%s> established", utils.FmtIp(m.proxy.Host), m.Addr, utils.Vtcp(m.IpV6)))
} else {
m.Logger.Info(fmt.Sprintf("connection to [%s] - <%s> established", utils.FmtIp(m.Addr), utils.Vtcp(m.IpV6)))
}
} else {
if m.proxy != nil && m.proxy.Host != "" {
m.Logger.Debug(fmt.Sprintf("connection to (~%s)[%s] - <%s> established", utils.FmtIp(m.proxy.Host), m.Addr, utils.Vtcp(m.IpV6)))
} else {
m.Logger.Debug(fmt.Sprintf("connection to [%s] - <%s> established", utils.FmtIp(m.Addr), utils.Vtcp(m.IpV6)))
}
}
m.startReadingResponses(ctx)
if !m.exported {
go m.longPing(ctx)
}
if !m.encrypted {
m.Logger.Debug("authKey not found, creating new one")
err = m.makeAuthKey()
if err != nil {
return err
}
m.Logger.Debug("authKey created and saved")
}
return nil
}
func (m *MTProto) connect(ctx context.Context) error {
var err error
m.transport, err = transport.NewTransport(
m,
transport.TCPConnConfig{
Ctx: ctx,
Host: utils.FmtIp(m.Addr),
IpV6: m.IpV6,
Timeout: defaultTimeout,
Socks: m.proxy,
},
m.mode,
)
if err != nil {
return fmt.Errorf("creating transport: %w", err)
}
return nil
}
func (m *MTProto) makeRequest(data tl.Object, expectedTypes ...reflect.Type) (any, error) {
for !m.TcpActive() {
time.Sleep(20 * time.Millisecond)
}
resp, _, err := m.sendPacket(data, expectedTypes...)
if err != nil {
if strings.Contains(err.Error(), "use of closed network connection") || strings.Contains(err.Error(), "transport is closed") || strings.Contains(err.Error(), "connection was forcibly closed") || strings.Contains(err.Error(), "connection reset by peer") || strings.Contains(err.Error(), "broken pipe") {
m.Logger.Info(fmt.Sprintf("connection closed due to broken tcp, reconnecting to [%s] - <%s> ...", m.Addr, utils.Vtcp(m.IpV6)))
err = m.Reconnect(false)
if err != nil {
return nil, errors.Wrap(err, "reconnecting")
}
return m.makeRequest(data, expectedTypes...)
}
return nil, errors.Wrap(err, "sending packet")
}
response := <-resp
switch r := response.(type) {
case *objects.RpcError:
if err := RpcErrorToNative(r).(*ErrResponseCode); strings.Contains(err.Message, "FLOOD_WAIT_") || strings.Contains(err.Message, "FLOOD_PREMIUM_WAIT_") {
if done := m.floodHandler(err); !done {
return nil, RpcErrorToNative(r)
} else {
return m.makeRequest(data, expectedTypes...)
}
}
m.errorHandler(RpcErrorToNative(r))
return nil, RpcErrorToNative(r)
case *errorSessionConfigsChanged:
m.Logger.Debug("session configs changed, resending request")
return m.makeRequest(data, expectedTypes...)
}
return tl.UnwrapNativeTypes(response), nil
}
func (m *MTProto) makeRequestCtx(ctx context.Context, data tl.Object, expectedTypes ...reflect.Type) (any, error) {
for !m.TcpActive() {
time.Sleep(20 * time.Millisecond)
}
resp, msgId, err := m.sendPacket(data, expectedTypes...)
if err != nil {
if strings.Contains(err.Error(), "use of closed network connection") || strings.Contains(err.Error(), "transport is closed") || strings.Contains(err.Error(), "connection was forcibly closed") || strings.Contains(err.Error(), "connection reset by peer") || strings.Contains(err.Error(), "broken pipe") {
m.Logger.Info("connection closed due to broken tcp, reconnecting to [" + m.Addr + "]" + " - <Tcp> ...")
err = m.Reconnect(false)
if err != nil {
return nil, errors.Wrap(err, "reconnecting")
}
return m.makeRequestCtx(ctx, data, expectedTypes...)
}
return nil, errors.Wrap(err, "sending packet")
}
select {
case <-ctx.Done():
go m.writeRPCResponse(int(msgId), &objects.Null{})
return nil, ctx.Err()
case response := <-resp:
switch r := response.(type) {
case *objects.RpcError:
if err := RpcErrorToNative(r).(*ErrResponseCode); strings.Contains(err.Message, "FLOOD_WAIT_") || strings.Contains(err.Message, "FLOOD_PREMIUM_WAIT_") {
if done := m.floodHandler(err); !done {
return nil, RpcErrorToNative(r)
} else {
return m.makeRequestCtx(ctx, data, expectedTypes...)
}
}
return nil, RpcErrorToNative(r)
case *errorSessionConfigsChanged:
m.Logger.Debug("session configs changed, resending request")
return m.makeRequestCtx(ctx, data, 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 errors.Wrap(err, "sending packet")
}
return err
}
func (m *MTProto) TcpActive() bool {
return m.tcpActive.Load()
}
func (m *MTProto) stopRoutines() {
if m.ctxCancel != nil {
m.ctxCancel()
}
}
func (m *MTProto) Disconnect() error {
m.tcpActive.Store(false)
m.stopRoutines()
return nil
}
func (m *MTProto) Terminate() error {
m.stopRoutines()
m.responseChannels.Close()
m.transport.Close()
m.tcpActive.Store(false)
return nil
}
func (m *MTProto) Reconnect(WithLogs bool) error {
err := m.Disconnect()
if err != nil {
return errors.Wrap(err, "disconnecting")
}
if WithLogs {
m.Logger.Info(fmt.Sprintf("reconnecting to [%s] - <Tcp> ...", m.Addr))
}
err = m.CreateConnection(WithLogs)
if err == nil && WithLogs {
m.Logger.Info(fmt.Sprintf("reconnected to [%s] - <Tcp>", m.Addr))
}
m.Ping()
return errors.Wrap(err, "recreating connection")
}
// keep pinging to keep the connection alive
func (m *MTProto) longPing(ctx context.Context) {
m.routineswg.Add(1)
defer m.routineswg.Done()
for {
select {
case <-ctx.Done():
return
default:
if !m.TcpActive() {
m.Logger.Warn("connection is not established with, stopping Ping routine")
return
}
time.Sleep(30 * time.Second)
m.Ping()
}
}
}
func (m *MTProto) Ping() time.Duration {
start := time.Now()
m.InvokeRequestWithoutUpdate(&utils.PingParams{
PingID: time.Now().Unix(),
})
return time.Since(start)
}
func (m *MTProto) startReadingResponses(ctx context.Context) {
m.routineswg.Add(1)
go func() {
defer m.routineswg.Done()
for {
select {
case <-ctx.Done():
return
default:
if !m.tcpActive.Load() {
m.Logger.Warn("connection is not established with, stopping Updates Queue")
return
}
err := m.readMsg()
if err != nil {
if strings.Contains(err.Error(), "unexpected error: unexpected EOF") {
m.Logger.Debug("tcp connection closed, reconnecting to [" + m.Addr + "] - <Tcp> ...")
err = m.Reconnect(false)
if err != nil {
m.Logger.Error(errors.Wrap(err, "reconnecting"))
}
} else if strings.Contains(err.Error(), "required to reconnect!") { // network is not stable
m.Logger.Debug("packet read error, reconnecting to [" + m.Addr + "] - <Tcp> ...")
err = m.Reconnect(false)
if err != nil {
m.Logger.Error(errors.Wrap(err, "reconnecting"))
}
}
}
switch err {
case nil:
case context.Canceled:
return
case io.EOF:
m.Logger.Debug("eof error, reconnecting to [" + m.Addr + "] - <Tcp> ...")
err = m.Reconnect(false)
if err != nil {
m.Logger.Error(errors.Wrap(err, "reconnecting"))
}
return
default:
switch e := err.(type) {
case *ErrResponseCode:
if e.Code == 4294966892 {
m.handle404Error()
} else {
m.Logger.Debug(errors.New("[RESPONSE_ERROR_CODE] - " + e.Error()))
}
case *transport.ErrCode:
m.Logger.Error(errors.New("[TRANSPORT_ERROR_CODE] - " + e.Error()))
}
m.Logger.Debug(errors.Wrap(err, "reading message"))
if err := m.Reconnect(false); err != nil {
m.Logger.Error(errors.Wrap(err, "reconnecting"))
}
}
}
}
}()
}
func (m *MTProto) handle404Error() {
if m.authKey404[0] == 0 && m.authKey404[1] == 0 {
m.authKey404 = [2]int64{1, time.Now().Unix()}
} else {
currentTime := time.Now().Unix()
if currentTime-m.authKey404[1] < 2 { // time frame to check if the error is repeating
m.authKey404[0]++
} else {
m.authKey404 = [2]int64{1, currentTime}
}
}
if m.authKey404[0] == 4 {
m.Logger.Debug("-404 (x4), refreshing connection pipline")
err := m.Reconnect(false)
if err != nil {
m.Logger.Error(errors.Wrap(err, "reconnecting"))
}
} else if m.authKey404[0] > 8 && m.authKey404[0] < 16 {
m.Logger.Debug("-404 (x8), reloading session")
m.LoadSession(m.sessionBackup)
if err := m.SaveSession(m.memorySession); err != nil {
m.Logger.Error(errors.Wrap(err, "saving session"))
}
if err := m.Reconnect(false); err != nil {
m.Logger.Error(errors.Wrap(err, "reconnecting"))
}
} else if m.authKey404[0] > 16 {
panic("[AUTH_KEY_INVALID] (code -404) - too many failures")
}
}
func (m *MTProto) readMsg() error {
if m.transport == nil {
return errors.New("must setup connection before reading messages")
}
response, err := m.transport.ReadMsg()
if err != nil {
if e, ok := err.(transport.ErrCode); ok {
return &ErrResponseCode{Code: int64(e)}
}
switch err {
case io.EOF, context.Canceled:
return err
default:
return errors.Wrap(err, "reading message")
}
}
if m.serviceModeActivated {
var obj tl.Object
obj, err = tl.DecodeUnknownObject(response.GetMsg())
if err != nil {
return errors.Wrap(err, "parsing object")
}
m.serviceChannel <- obj
return nil
}
err = m.processResponse(response)
if err != nil {
m.Logger.Debug(errors.Wrap(err, "decoding unknown object"))
return errors.Wrap(err, "incoming update")
}
return nil
}
func (m *MTProto) processResponse(msg messages.Common) error {
var data tl.Object
var err error
if (msg.GetSeqNo() & 1) != 0 {
msgID := int64(msg.GetMsgID())
if m.pendingAcks.Has(msgID) {
return nil
} else {
m.pendingAcks.Add(msgID)
}
}
if et, ok := m.expectedTypes.Get(msg.GetMsgID()); ok && len(et) > 0 {
data, err = tl.DecodeUnknownObject(msg.GetMsg(), et...)
} else {
data, err = tl.DecodeUnknownObject(msg.GetMsg())
}
if err != nil {
return fmt.Errorf("unmarshalling response: %w", err)
}
messageTypeSwitching:
switch message := data.(type) {
case *objects.MessageContainer:
for _, v := range *message {
err := m.processResponse(v)
if err != nil {
return errors.Wrap(err, "processing item in container")
}
}
case *objects.BadServerSalt:
m.serverSalt = message.NewSalt
if err := m.SaveSession(m.memorySession); err != nil {
return errors.Wrap(err, "saving session")
}
var respChannelsBackup *utils.SyncIntObjectChan
m.mutex.Lock()
defer m.mutex.Unlock()
respChannelsBackup = m.responseChannels
m.responseChannels = utils.NewSyncIntObjectChan()
for _, k := range respChannelsBackup.Keys() {
if v, ok := respChannelsBackup.Get(k); ok {
respChannelsBackup.Delete(k)
select {
case v <- &errorSessionConfigsChanged{}:
case <-time.After(1 * time.Millisecond):
}
}
}
case *objects.NewSessionCreated:
m.serverSalt = message.ServerSalt
if err := m.SaveSession(m.memorySession); err != nil {
m.Logger.Error(errors.Wrap(err, "saving session"))
}
case *objects.MsgsNewDetailedInfo:
m.pendingAcks.Add(message.AnswerMsgID)
return nil
case *objects.MsgsDetailedInfo:
m.pendingAcks.Add(message.AnswerMsgID)
return nil
case *objects.Pong:
m.Logger.Debug("rpc - ping: " + fmt.Sprintf("%T", message))
case *objects.MsgsAck:
// do nothing
case *objects.BadMsgNotification:
badMsg := BadMsgErrorFromNative(message)
if badMsg.Code == 16 || badMsg.Code == 17 {
m.offsetTime()
}
m.Logger.Debug("bad-msg-notification: " + badMsg.Error())
return badMsg
case *objects.RpcResult:
obj := message.Obj
if v, ok := obj.(*objects.GzipPacked); ok {
obj = v.Obj
}
m.Logger.Debug("rpc - response: " + fmt.Sprintf("%T", obj))
err := m.writeRPCResponse(int(message.ReqMsgID), obj)
if err != nil {
if strings.Contains(err.Error(), "no response channel found") {
m.Logger.Debug(errors.Wrap(err, "writing rpc response"))
} else {
return errors.Wrap(err, "writing rpc response")
}
}
case *objects.GzipPacked:
// sometimes telegram server returns gzip for unknown reason. so, we are extracting data from gzip and
// reprocess it again
data = message.Obj
goto messageTypeSwitching
default:
processed := false
for _, f := range m.serverRequestHandlers {
processed = f(message)
if processed {
break
}
}
if !processed {
m.Logger.Debug("unhandled update: " + fmt.Sprintf("%T", message))
}
}
if m.pendingAcks.Len() >= acksThreshold {
m.Logger.Debug("Sending acks", m.pendingAcks.Len())
_, err := m.MakeRequest(&objects.MsgsAck{MsgIDs: m.pendingAcks.Keys()})
if err != nil {
return errors.Wrap(err, "sending acks")
}
m.pendingAcks.Clear()
}
return nil
}
func MessageRequireToAck(msg tl.Object) bool {
switch msg.(type) {
case *objects.MsgsAck:
return false
default:
return true
}
}
func (m *MTProto) offsetTime() {
currentLocalTime := time.Now().Unix()
client := http.Client{Timeout: 2 * time.Second}
resp, err := client.Get("http://worldtimeapi.org/api/ip")
if err != nil {
return
}
defer resp.Body.Close()
var timeResponse struct {
Unixtime int64 `json:"unixtime"`
}
if err := json.NewDecoder(resp.Body).Decode(&timeResponse); err != nil {
return
}
if timeResponse.Unixtime <= currentLocalTime || math.Abs(float64(timeResponse.Unixtime-currentLocalTime)) < 60 {
return // -no need to offset time
}
m.timeOffset = timeResponse.Unixtime - currentLocalTime
m.Logger.Info("system time is out of sync, offsetting time by " + strconv.FormatInt(m.timeOffset, 10) + " seconds")
}