-
Notifications
You must be signed in to change notification settings - Fork 241
/
client.go
1671 lines (1406 loc) · 53.4 KB
/
client.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
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
package pushnotificationclient
import (
"bytes"
"context"
"crypto/aes"
"crypto/cipher"
"crypto/ecdsa"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"io"
"math"
mrand "math/rand"
"time"
"github.com/golang/protobuf/proto"
"github.com/google/uuid"
"go.uber.org/zap"
"github.com/status-im/status-go/eth-node/crypto"
"github.com/status-im/status-go/eth-node/crypto/ecies"
"github.com/status-im/status-go/eth-node/types"
"github.com/status-im/status-go/protocol/common"
"github.com/status-im/status-go/protocol/protobuf"
)
// How does sending notifications work?
// 1) Every time a message is scheduled for sending, it will be received on a channel.
// we keep track on whether we should send a push notification for this message.
// 2) Every time a message is dispatched, we check whether we should send a notification.
// If so, we query the user info if necessary, check which installations we should be targeting
// and notify the server if we have information about the user (i.e a token).
// The logic is complicated by the fact that sometimes messages are batched together (datasync)
// and the fact that sometimes we send messages to all devices (dh messages).
// 3) The server will notify us if the wrong token is used, in which case a loop will be started that
// will re-query and re-send the notification, up to a maximum.
// How does registering works?
// We register with the server asynchronously, through a loop, that will try to make sure that
// we have registered with all the servers added, until eventually it gives up.
// A lot of the logic is complicated by the fact that waku/whisper is not req/response, so we just fire a message
// hoping to get a reply at some later stages.
const encryptedPayloadKeyLength = 16
const accessTokenKeyLength = 16
const staleQueryTimeInSeconds = 86400
const mentionInstallationID = "mention"
const oneToOneChatIDLength = 132
// maxRegistrationRetries is the maximum number of attempts we do before giving up registering with a server
const maxRegistrationRetries int64 = 12
// maxPushNotificationRetries is the maximum number of attempts before we give up sending a push notification
const maxPushNotificationRetries int64 = 4
// pushNotificationBackoffTime is the step of the exponential backoff
const pushNotificationBackoffTime int64 = 2
// RegistrationBackoffTime is the step of the exponential backoff
const RegistrationBackoffTime int64 = 15
// defaultPushNotificationsServerCount is how many push notification servers we should register with if none is selected
const defaultPushNotificationsServersCount = 3
type ServerType int
const (
ServerTypeDefault = iota + 1
ServerTypeCustom
)
type PushNotificationServer struct {
PublicKey *ecdsa.PublicKey `json:"-"`
Registered bool `json:"registered,omitempty"`
RegisteredAt int64 `json:"registeredAt,omitempty"`
LastRetriedAt int64 `json:"lastRetriedAt,omitempty"`
RetryCount int64 `json:"retryCount,omitempty"`
AccessToken string `json:"accessToken,omitempty"`
Type ServerType `json:"type,omitempty"`
}
func (s *PushNotificationServer) MarshalJSON() ([]byte, error) {
type ServerAlias PushNotificationServer
item := struct {
*ServerAlias
PublicKeyString string `json:"publicKey"`
}{
ServerAlias: (*ServerAlias)(s),
PublicKeyString: types.EncodeHex(crypto.FromECDSAPub(s.PublicKey)),
}
return json.Marshal(item)
}
type PushNotificationInfo struct {
AccessToken string
InstallationID string
PublicKey *ecdsa.PublicKey
ServerPublicKey *ecdsa.PublicKey
RetrievedAt int64
Version uint64
}
type SentNotification struct {
PublicKey *ecdsa.PublicKey
InstallationID string
LastTriedAt int64
RetryCount int64
MessageID []byte
ChatID string
NotificationType protobuf.PushNotification_PushNotificationType
Success bool
Error protobuf.PushNotificationReport_ErrorType
}
type RegistrationOptions struct {
PublicChatIDs []string
MutedChatIDs []string
ContactIDs []*ecdsa.PublicKey
}
func (s *SentNotification) HashedPublicKey() []byte {
return common.HashPublicKey(s.PublicKey)
}
type Config struct {
// Identity is our identity key
Identity *ecdsa.PrivateKey
// SendEnabled indicates whether we should be sending push notifications
SendEnabled bool
// RemoteNotificationsEnabled is whether we should register with a remote server for push notifications
RemoteNotificationsEnabled bool
// AllowyFromContactsOnly indicates whether we should be receiving push notifications
// only from contacts
AllowFromContactsOnly bool
// BlockMentions indicates whether we should not receive notification for mentions
BlockMentions bool
// InstallationID is the installation-id for this device
InstallationID string
Logger *zap.Logger
// DefaultServers holds the push notification servers used by
// default if none is selected
DefaultServers []*ecdsa.PublicKey
}
type MessagePersistence interface {
MessageByID(string) (*common.Message, error)
}
type Client struct {
persistence *Persistence
messagePersistence MessagePersistence
config *Config
// lastPushNotificationRegistration is the latest known push notification version
lastPushNotificationRegistration *protobuf.PushNotificationRegistration
// lastContactIDs is the latest contact ids array
lastContactIDs []*ecdsa.PublicKey
// AccessToken is the access token that is currently being used
AccessToken string
// deviceToken is the device token for this device
deviceToken string
// TokenType is the type of token
tokenType protobuf.PushNotificationRegistration_TokenType
// APNTopic is the topic of the apn topic for push notification
apnTopic string
// randomReader only used for testing so we have deterministic encryption
reader io.Reader
//messageProcessor is a message processor used to send and being notified of messages
messageProcessor *common.MessageProcessor
// registrationLoopQuitChan is a channel to indicate to the registration loop that should be terminating
registrationLoopQuitChan chan struct{}
// resendingLoopQuitChan is a channel to indicate to the send loop that should be terminating
resendingLoopQuitChan chan struct{}
quit chan struct{}
// registrationSubscriptions is a list of chan of client subscribed to the registration event
registrationSubscriptions []chan struct{}
}
func New(persistence *Persistence, config *Config, processor *common.MessageProcessor, messagePersistence MessagePersistence) *Client {
return &Client{
quit: make(chan struct{}),
config: config,
messageProcessor: processor,
messagePersistence: messagePersistence,
persistence: persistence,
reader: rand.Reader,
}
}
func (c *Client) Start() error {
if c.messageProcessor == nil {
return errors.New("can't start, missing message processor")
}
err := c.loadLastPushNotificationRegistration()
if err != nil {
return err
}
c.subscribeForMessageEvents()
// We start even if push notifications are disabled, as we might
// actually be sending an unregister message
c.startRegistrationLoop()
c.startResendingLoop()
return nil
}
func (c *Client) Offline() {
c.stopRegistrationLoop()
c.stopResendingLoop()
}
func (c *Client) Online() {
c.startRegistrationLoop()
c.startResendingLoop()
}
func (c *Client) publishOnRegistrationSubscriptions() {
// Publish on channels, drop if buffer is full
for _, s := range c.registrationSubscriptions {
select {
case s <- struct{}{}:
default:
c.config.Logger.Warn("subscription channel full, dropping message")
}
}
}
func (c *Client) quitRegistrationSubscriptions() {
for _, s := range c.registrationSubscriptions {
close(s)
}
}
func (c *Client) Stop() error {
close(c.quit)
c.stopRegistrationLoop()
c.stopResendingLoop()
c.quitRegistrationSubscriptions()
return nil
}
// Unregister unregisters from all the servers
func (c *Client) Unregister() error {
// stop registration loop
c.stopRegistrationLoop()
c.config.RemoteNotificationsEnabled = false
registration := c.buildPushNotificationUnregisterMessage()
err := c.saveLastPushNotificationRegistration(registration, nil)
if err != nil {
return err
}
// reset servers
err = c.resetServers()
if err != nil {
return err
}
// and asynchronously register
c.startRegistrationLoop()
return nil
}
// Registered returns true if we registered with all the servers
func (c *Client) Registered() (bool, error) {
servers, err := c.persistence.GetServers()
if err != nil {
return false, err
}
for _, s := range servers {
if !s.Registered {
return false, nil
}
}
return true, nil
}
func (c *Client) SubscribeToRegistrations() chan struct{} {
s := make(chan struct{}, 100)
c.registrationSubscriptions = append(c.registrationSubscriptions, s)
return s
}
func (c *Client) GetSentNotification(hashedPublicKey []byte, installationID string, messageID []byte) (*SentNotification, error) {
return c.persistence.GetSentNotification(hashedPublicKey, installationID, messageID)
}
func (c *Client) GetServers() ([]*PushNotificationServer, error) {
return c.persistence.GetServers()
}
func (c *Client) Reregister(options *RegistrationOptions) error {
c.config.Logger.Debug("re-registering")
if len(c.deviceToken) == 0 {
c.config.Logger.Info("no device token, not registering")
return nil
}
if !c.config.RemoteNotificationsEnabled {
c.config.Logger.Info("remote notifications not enabled, not registering")
return nil
}
return c.Register(c.deviceToken, c.apnTopic, c.tokenType, options)
}
// pickDefaultServesr picks n servers at random
func (c *Client) pickDefaultServers(servers []*ecdsa.PublicKey) []*ecdsa.PublicKey {
// shuffle and pick n at random
shuffledServers := make([]*ecdsa.PublicKey, len(servers))
copy(shuffledServers, c.config.DefaultServers)
mrand.Seed(time.Now().Unix())
mrand.Shuffle(len(shuffledServers), func(i, j int) {
shuffledServers[i], shuffledServers[j] = shuffledServers[j], shuffledServers[i]
})
// Take the min not to get an out of bounds slice
min := len(c.config.DefaultServers)
if min > defaultPushNotificationsServersCount {
min = defaultPushNotificationsServersCount
}
return shuffledServers[:min]
}
// Register registers with all the servers
func (c *Client) Register(deviceToken, apnTopic string, tokenType protobuf.PushNotificationRegistration_TokenType, options *RegistrationOptions) error {
// stop registration loop
c.stopRegistrationLoop()
c.config.RemoteNotificationsEnabled = true
// check if we need to fallback on default servers
currentServers, err := c.persistence.GetServers()
if err != nil {
return err
}
if len(currentServers) == 0 && len(c.config.DefaultServers) != 0 {
c.config.Logger.Debug("servers empty, checking default servers")
for _, s := range c.pickDefaultServers(c.config.DefaultServers) {
err = c.AddPushNotificationsServer(s, ServerTypeDefault)
if err != nil {
return err
}
}
}
// reset servers
err = c.resetServers()
if err != nil {
return err
}
c.deviceToken = deviceToken
c.apnTopic = apnTopic
c.tokenType = tokenType
registration, err := c.buildPushNotificationRegistrationMessage(options)
if err != nil {
return err
}
err = c.saveLastPushNotificationRegistration(registration, options.ContactIDs)
if err != nil {
return err
}
c.startRegistrationLoop()
return nil
}
// HandlePushNotificationRegistrationResponse should check whether the response was successful or not, retry if necessary otherwise store the result in the database
func (c *Client) HandlePushNotificationRegistrationResponse(publicKey *ecdsa.PublicKey, response protobuf.PushNotificationRegistrationResponse) error {
c.config.Logger.Debug("received push notification registration response", zap.Any("response", response))
// Not successful ignore for now
if !response.Success {
return errors.New("response was not successful")
}
servers, err := c.persistence.GetServersByPublicKey([]*ecdsa.PublicKey{publicKey})
if err != nil {
return err
}
// we haven't registered with this server
if len(servers) != 1 {
return errors.New("not registered with this server, ignoring")
}
server := servers[0]
server.Registered = true
server.RegisteredAt = time.Now().Unix()
err = c.persistence.UpsertServer(server)
if err != nil {
return err
}
c.publishOnRegistrationSubscriptions()
return nil
}
// processQueryInfo takes info about push notifications and validates them
func (c *Client) processQueryInfo(clientPublicKey *ecdsa.PublicKey, serverPublicKey *ecdsa.PublicKey, info *protobuf.PushNotificationQueryInfo) error {
// make sure the public key matches
if !bytes.Equal(info.PublicKey, common.HashPublicKey(clientPublicKey)) {
c.config.Logger.Warn("reply for different key, ignoring")
return errors.New("reply for a different key, ignoring")
}
accessToken := info.AccessToken
// the user wants notification from contacts only, try to decrypt the access token to see if we are in their contacts
if len(accessToken) == 0 && len(info.AllowedKeyList) != 0 {
accessToken = c.handleAllowedKeyList(clientPublicKey, info.AllowedKeyList)
}
// no luck
if len(accessToken) == 0 {
c.config.Logger.Debug("not in the allowed key list")
return nil
}
// We check the user has allowed this server to store this particular
// access token, otherwise anyone could reply with a fake token
// and receive notifications for a user
if err := c.handleGrant(clientPublicKey, serverPublicKey, info.Grant, accessToken); err != nil {
c.config.Logger.Warn("grant verification failed, ignoring", zap.Error(err))
return err
}
pushNotificationInfo := &PushNotificationInfo{
PublicKey: clientPublicKey,
ServerPublicKey: serverPublicKey,
AccessToken: accessToken,
InstallationID: info.InstallationId,
Version: info.Version,
RetrievedAt: time.Now().Unix(),
}
err := c.persistence.SavePushNotificationInfo([]*PushNotificationInfo{pushNotificationInfo})
if err != nil {
c.config.Logger.Error("failed to save push notifications", zap.Error(err))
return err
}
return nil
}
// HandlePushNotificationQueryResponse should update the data in the database for a given user
func (c *Client) HandlePushNotificationQueryResponse(serverPublicKey *ecdsa.PublicKey, response protobuf.PushNotificationQueryResponse) error {
c.config.Logger.Debug("received push notification query response", zap.Any("response", response))
if len(response.Info) == 0 {
return errors.New("empty response from the server")
}
// get the public key associated with this query
clientPublicKey, err := c.persistence.GetQueryPublicKey(response.MessageId)
if err != nil {
return err
}
if clientPublicKey == nil {
c.config.Logger.Debug("query not found")
return nil
}
// process query, make sure to validate grant as coming from the server
for _, info := range response.Info {
err := c.processQueryInfo(clientPublicKey, serverPublicKey, info)
if err != nil {
c.config.Logger.Warn("failed to process info", zap.Any("info", info), zap.Error(err))
continue
}
}
return nil
}
// HandleContactCodeAdvertisement checks if there are any info and process them
func (c *Client) HandleContactCodeAdvertisement(clientPublicKey *ecdsa.PublicKey, message protobuf.ContactCodeAdvertisement) error {
// nothing to do for our own pubkey
if common.IsPubKeyEqual(clientPublicKey, &c.config.Identity.PublicKey) {
return nil
}
c.config.Logger.Debug("received contact code advertisement", zap.Any("advertisement", message))
for _, info := range message.PushNotificationInfo {
c.config.Logger.Debug("handling push notification query info")
serverPublicKey, err := crypto.DecompressPubkey(info.ServerPublicKey)
if err != nil {
c.config.Logger.Error("could not unmarshal server pubkey", zap.Binary("server-key", info.ServerPublicKey))
return err
}
err = c.processQueryInfo(clientPublicKey, serverPublicKey, info)
if err != nil {
return err
}
}
// Save query so that we won't query again to early
// NOTE: this is not very accurate as we might fetch an historical message,
// prolonging the time that we fetch new info.
// Most of the times it should work fine, as if the info are stale they'd be
// fetched again because of an error response from the push notification server
return c.persistence.SavePushNotificationQuery(clientPublicKey, []byte(uuid.New().String()))
}
// HandlePushNotificationResponse should set the request as processed
func (c *Client) HandlePushNotificationResponse(serverKey *ecdsa.PublicKey, response protobuf.PushNotificationResponse) error {
messageID := response.MessageId
c.config.Logger.Debug("received response for", zap.Binary("message-id", messageID))
for _, report := range response.Reports {
c.config.Logger.Debug("received response", zap.Any("report", report))
err := c.persistence.UpdateNotificationResponse(messageID, report)
if err != nil {
return err
}
}
// Restart resending loop, in case we need to resend some notifications
c.stopResendingLoop()
c.startResendingLoop()
return nil
}
func (c *Client) RemovePushNotificationServer(publicKey *ecdsa.PublicKey) error {
c.config.Logger.Debug("removing push notification server", zap.Any("public-key", publicKey))
//TODO: this needs implementing. It requires unregistering from the server and
// likely invalidate the device token of the user
return errors.New("not implemented")
}
func (c *Client) AddPushNotificationsServer(publicKey *ecdsa.PublicKey, serverType ServerType) error {
c.config.Logger.Debug("adding push notifications server", zap.Any("public-key", publicKey))
currentServers, err := c.persistence.GetServers()
if err != nil {
return err
}
for _, server := range currentServers {
if common.IsPubKeyEqual(server.PublicKey, publicKey) {
return errors.New("push notification server already added")
}
}
err = c.persistence.UpsertServer(&PushNotificationServer{
PublicKey: publicKey,
Type: serverType,
})
if err != nil {
return err
}
if c.config.RemoteNotificationsEnabled {
c.startRegistrationLoop()
}
return nil
}
func (c *Client) GetPushNotificationInfo(publicKey *ecdsa.PublicKey, installationIDs []string) ([]*PushNotificationInfo, error) {
if len(installationIDs) == 0 {
return c.persistence.GetPushNotificationInfoByPublicKey(publicKey)
}
return c.persistence.GetPushNotificationInfo(publicKey, installationIDs)
}
func (c *Client) Enabled() bool {
return c.config.RemoteNotificationsEnabled
}
func (c *Client) EnableSending() {
c.config.SendEnabled = true
}
func (c *Client) DisableSending() {
c.config.SendEnabled = false
}
func (c *Client) EnablePushNotificationsFromContactsOnly(options *RegistrationOptions) error {
c.config.Logger.Debug("enabling push notification from contacts only")
c.config.AllowFromContactsOnly = true
if c.lastPushNotificationRegistration != nil && c.config.RemoteNotificationsEnabled {
c.config.Logger.Debug("re-registering after enabling push notifications from contacts only")
return c.Register(c.deviceToken, c.apnTopic, c.tokenType, options)
}
return nil
}
func (c *Client) DisablePushNotificationsFromContactsOnly(options *RegistrationOptions) error {
c.config.Logger.Debug("disabling push notification from contacts only")
c.config.AllowFromContactsOnly = false
if c.lastPushNotificationRegistration != nil && c.config.RemoteNotificationsEnabled {
c.config.Logger.Debug("re-registering after disabling push notifications from contacts only")
return c.Register(c.deviceToken, c.apnTopic, c.tokenType, options)
}
return nil
}
func (c *Client) EnablePushNotificationsBlockMentions(options *RegistrationOptions) error {
c.config.Logger.Debug("disabling push notifications for mentions")
c.config.BlockMentions = true
if c.lastPushNotificationRegistration != nil && c.config.RemoteNotificationsEnabled {
c.config.Logger.Debug("re-registering after disabling push notifications for mentions")
return c.Register(c.deviceToken, c.apnTopic, c.tokenType, options)
}
return nil
}
func (c *Client) DisablePushNotificationsBlockMentions(options *RegistrationOptions) error {
c.config.Logger.Debug("enabling push notifications for mentions")
c.config.BlockMentions = false
if c.lastPushNotificationRegistration != nil && c.config.RemoteNotificationsEnabled {
c.config.Logger.Debug("re-registering after enabling push notifications for mentions")
return c.Register(c.deviceToken, c.apnTopic, c.tokenType, options)
}
return nil
}
func encryptAccessToken(plaintext []byte, key []byte, reader io.Reader) ([]byte, error) {
c, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(reader, nonce); err != nil {
return nil, err
}
return gcm.Seal(nonce, nonce, plaintext, nil), nil
}
func (c *Client) encryptRegistration(publicKey *ecdsa.PublicKey, payload []byte) ([]byte, error) {
sharedKey, err := c.generateSharedKey(publicKey)
if err != nil {
return nil, err
}
return common.Encrypt(payload, sharedKey, c.reader)
}
func (c *Client) generateSharedKey(publicKey *ecdsa.PublicKey) ([]byte, error) {
return ecies.ImportECDSA(c.config.Identity).GenerateShared(
ecies.ImportECDSAPublic(publicKey),
encryptedPayloadKeyLength,
encryptedPayloadKeyLength,
)
}
// subscribeForMessageEvents subscribes for newly sent/scheduled messages so we can check if we need to send a push notification
func (c *Client) subscribeForMessageEvents() {
go func() {
c.config.Logger.Debug("subscribing for message events")
sentMessagesSubscription := c.messageProcessor.SubscribeToSentMessages()
scheduledMessagesSubscription := c.messageProcessor.SubscribeToScheduledMessages()
for {
select {
// order is important, since both are asynchronous, we want to process
// first scheduled messages, and after sent messages, otherwise we might
// have some race conditions.
// This does not completely rules them out, but reduced the window
// where it might happen, a single channel should be used
// if this actually happens.
case m, more := <-scheduledMessagesSubscription:
if !more {
c.config.Logger.Debug("no more scheduled messages, quitting")
return
}
c.config.Logger.Debug("handling message scheduled")
if err := c.handleMessageScheduled(m); err != nil {
c.config.Logger.Error("failed to handle message", zap.Error(err))
}
case m, more := <-sentMessagesSubscription:
if !more {
c.config.Logger.Debug("no more sent messages, quitting")
return
}
c.config.Logger.Debug("handling message sent")
if err := c.handleMessageSent(m); err != nil {
c.config.Logger.Error("failed to handle message", zap.Error(err))
}
case <-c.quit:
return
}
}
}()
}
// loadLastPushNotificationRegistration loads from the database the last registration
func (c *Client) loadLastPushNotificationRegistration() error {
lastRegistration, lastContactIDs, err := c.persistence.GetLastPushNotificationRegistration()
if err != nil {
return err
}
if lastRegistration == nil {
lastRegistration = &protobuf.PushNotificationRegistration{}
}
c.lastContactIDs = lastContactIDs
c.lastPushNotificationRegistration = lastRegistration
c.deviceToken = lastRegistration.DeviceToken
c.apnTopic = lastRegistration.ApnTopic
c.tokenType = lastRegistration.TokenType
return nil
}
func (c *Client) stopRegistrationLoop() {
// stop old registration loop
if c.registrationLoopQuitChan != nil {
close(c.registrationLoopQuitChan)
c.registrationLoopQuitChan = nil
}
}
func (c *Client) stopResendingLoop() {
// stop old registration loop
if c.resendingLoopQuitChan != nil {
close(c.resendingLoopQuitChan)
c.resendingLoopQuitChan = nil
}
}
func (c *Client) startRegistrationLoop() {
c.stopRegistrationLoop()
c.registrationLoopQuitChan = make(chan struct{})
go func() {
err := c.registrationLoop()
if err != nil {
c.config.Logger.Error("registration loop exited with an error", zap.Error(err))
}
}()
}
func (c *Client) startResendingLoop() {
c.stopResendingLoop()
c.resendingLoopQuitChan = make(chan struct{})
go func() {
err := c.resendingLoop()
if err != nil {
c.config.Logger.Error("resending loop exited with an error", zap.Error(err))
}
}()
}
// queryNotificationInfo will block and query for the client token, if force is set it
// will ignore the cool off period
func (c *Client) queryNotificationInfo(publicKey *ecdsa.PublicKey, force bool) error {
c.config.Logger.Debug("retrieving queried at")
// Check if we queried recently
queriedAt, err := c.persistence.GetQueriedAt(publicKey)
if err != nil {
c.config.Logger.Error("failed to retrieve queried at", zap.Error(err))
return err
}
c.config.Logger.Debug("checking if querying necessary")
// Naively query again if too much time has passed.
// Here it might not be necessary
if force || time.Now().Unix()-queriedAt > staleQueryTimeInSeconds {
c.config.Logger.Debug("querying info")
err := c.queryPushNotificationInfo(publicKey)
if err != nil {
c.config.Logger.Error("could not query pn info", zap.Error(err))
return err
}
// This is just horrible, but for now will do,
// the issue is that we don't really know how long it will
// take to reply, as there might be multiple servers
// replying to us.
// The only time we are 100% certain that we can proceed is
// when we have non-stale info for each device, but
// most devices are not going to be registered, so we'd still
// have to wait the maximum amount of time allowed.
// A better way to handle this is to set a maximum timer of say
// 3 seconds, but act at a tick every 200ms.
// That way we still are able to batch multiple push notifications
// but we don't have to wait every time 3 seconds, which is wasteful
// This probably will have to be addressed before released
time.Sleep(3 * time.Second)
}
return nil
}
// handleMessageSent is called every time a message is sent
func (c *Client) handleMessageSent(sentMessage *common.SentMessage) error {
// Ignore if we are not sending notifications
if !c.config.SendEnabled {
return nil
}
if sentMessage.PublicKey == nil {
return c.handlePublicMessageSent(sentMessage)
}
return c.handleDirectMessageSent(sentMessage)
}
// saving to the database might happen after we fetch the message, so we retry
// for a reasonable amount of time before giving up
func (c *Client) getMessage(messageID string) (*common.Message, error) {
retries := 0
for retries < 10 {
message, err := c.messagePersistence.MessageByID(messageID)
if err == common.ErrRecordNotFound {
retries++
time.Sleep(300 * time.Millisecond)
continue
} else if err != nil {
return nil, err
}
return message, nil
}
return nil, common.ErrRecordNotFound
}
// handlePublicMessageSent handles public messages, we notify only on mentions
func (c *Client) handlePublicMessageSent(sentMessage *common.SentMessage) error {
// We always expect a single message, as we never batch them
if len(sentMessage.MessageIDs) != 1 {
return errors.New("batched public messages not handled")
}
messageID := sentMessage.MessageIDs[0]
c.config.Logger.Debug("handling public messages", zap.Binary("messageID", messageID))
tracked, err := c.persistence.TrackedMessage(messageID)
if err != nil {
return err
}
if !tracked {
c.config.Logger.Debug("messageID not tracked, nothing to do", zap.Binary("messageID", messageID))
}
c.config.Logger.Debug("messageID tracked", zap.Binary("messageID", messageID))
message, err := c.getMessage(types.EncodeHex(messageID))
if err != nil {
c.config.Logger.Error("could not retrieve message", zap.Error(err))
}
// This might happen if the user deleted their messages for example
if message == nil {
c.config.Logger.Warn("message not retrieved")
return nil
}
c.config.Logger.Debug("message found", zap.Binary("messageID", messageID))
for _, pkString := range message.Mentions {
c.config.Logger.Debug("handling mention", zap.String("publickey", pkString))
pubkeyBytes, err := types.DecodeHex(pkString)
if err != nil {
return err
}
publicKey, err := crypto.UnmarshalPubkey(pubkeyBytes)
if err != nil {
return err
}
// we use a synthetic installationID for mentions, as all devices need to be notified
shouldNotify, err := c.shouldNotifyOn(publicKey, mentionInstallationID, messageID)
if err != nil {
return err
}
c.config.Logger.Debug("should no mention", zap.Any("publickey", shouldNotify))
// we send the notifications and return the info of the devices notified
infos, err := c.sendNotification(publicKey, nil, messageID, message.LocalChatID, protobuf.PushNotification_MENTION)
if err != nil {
return err
}
// mark message as sent so we don't notify again
for _, i := range infos {
c.config.Logger.Debug("marking as sent ", zap.Binary("mid", messageID), zap.String("id", i.InstallationID))
if err := c.notifiedOn(publicKey, i.InstallationID, messageID, message.LocalChatID, protobuf.PushNotification_MESSAGE); err != nil {
return err
}
}
}
return nil
}
// handleDirectMessageSent handles one to ones and private group chat messages
// It will check if we need to notify on the message, and if so it will try to
// dispatch a push notification messages might be batched, if coming
// from datasync for example.
func (c *Client) handleDirectMessageSent(sentMessage *common.SentMessage) error {
c.config.Logger.Debug("handling direct messages", zap.Any("messageIDs", sentMessage.MessageIDs))
publicKey := sentMessage.PublicKey
// Collect the messageIDs we want to notify on
var trackedMessageIDs [][]byte
for _, messageID := range sentMessage.MessageIDs {
tracked, err := c.persistence.TrackedMessage(messageID)
if err != nil {
return err
}
if tracked {
trackedMessageIDs = append(trackedMessageIDs, messageID)
}
}
// Nothing to do
if len(trackedMessageIDs) == 0 {
c.config.Logger.Debug("nothing to do for", zap.Any("messageIDs", sentMessage.MessageIDs))
return nil
}
// sendToAllDevices indicates whether the message has been sent using public key encryption only
// i.e not through the double ratchet. In that case, any device will have received it.
sendToAllDevices := len(sentMessage.Spec.Installations) == 0
var installationIDs []string
anyActionableMessage := sendToAllDevices
// Check if we should be notifiying those installations
for _, messageID := range trackedMessageIDs {
for _, installation := range sentMessage.Spec.Installations {
installationID := installation.ID
shouldNotify, err := c.shouldNotifyOn(publicKey, installationID, messageID)
if err != nil {
return err
}
if shouldNotify {
anyActionableMessage = true
installationIDs = append(installationIDs, installation.ID)
}
}
}
// Is there anything we should be notifying on?
if !anyActionableMessage {
c.config.Logger.Debug("no actionable installation IDs")
return nil
}
c.config.Logger.Debug("actionable messages", zap.Any("message-ids", trackedMessageIDs), zap.Any("installation-ids", installationIDs))
// Get message to check chatID. Again we use the first message for simplicity, but we should send one for each chatID. Messages though are very rarely batched.
message, err := c.getMessage(types.EncodeHex(trackedMessageIDs[0]))
if err != nil {
return err
}
// This is not the prettiest.
// because chatIDs are asymettric, we need to check if it's a one-to-one message or a group chat message.
// to do that we fingerprint the chatID.
// If it's a public key, we use our own public key as chatID, which correspond to the chatID used by the other peer
// otherwise we use the group chat ID
var chatID string
if len(message.ChatId) == oneToOneChatIDLength {
chatID = types.EncodeHex(crypto.FromECDSAPub(&c.config.Identity.PublicKey))
} else {
// this is a group chat
chatID = message.ChatId
}
// we send the notifications and return the info of the devices notified