forked from textileio/go-textile
/
handlers.go
612 lines (551 loc) · 16 KB
/
handlers.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
package service
import (
"bytes"
"errors"
"fmt"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/any"
"github.com/segmentio/ksuid"
"github.com/textileio/textile-go/crypto"
"github.com/textileio/textile-go/pb"
"github.com/textileio/textile-go/repo"
"github.com/textileio/textile-go/util"
"gx/ipfs/QmZoWKhxUmZ2seW4BzX6fJkNR8hh9PsGModr7q171yq2SS/go-libp2p-peer"
libp2pc "gx/ipfs/QmaPbCnUMBohSGo3KnxEa2bHqyJVVeEEcwtqJAYxerieBo/go-libp2p-crypto"
"gx/ipfs/QmcZfnkapfECQGcLZaf9B79NRg7cRa9EnZh4LSbkCzwNvY/go-cid"
"gx/ipfs/Qmej7nf81hi2x2tvjRBF3mcp74sQyuDH4VMYDGd1YtXjb2/go-block-format"
)
func (s *TextileService) HandlerForMsgType(t pb.Message_Type) func(peer.ID, *pb.Envelope, interface{}) (*pb.Envelope, error) {
switch t {
case pb.Message_PING:
return s.handlePing
case pb.Message_THREAD_INVITE:
return s.handleThreadInvite
case pb.Message_THREAD_JOIN:
return s.handleThreadJoin
case pb.Message_THREAD_LEAVE:
return s.handleThreadLeave
case pb.Message_THREAD_DATA:
return s.handleThreadData
case pb.Message_THREAD_ANNOTATION:
return s.handleThreadAnnotation
case pb.Message_THREAD_IGNORE:
return s.handleThreadIgnore
case pb.Message_THREAD_MERGE:
return s.handleThreadMerge
case pb.Message_OFFLINE_ACK:
return s.handleOfflineAck
case pb.Message_OFFLINE_RELAY:
return s.handleOfflineRelay
case pb.Message_BLOCK:
return s.handleBlock
case pb.Message_STORE:
return s.handleStore
case pb.Message_ERROR:
return s.handleError
default:
return nil
}
}
func (s *TextileService) handlePing(pid peer.ID, pmes *pb.Envelope, options interface{}) (*pb.Envelope, error) {
log.Debugf("received PING message from %s", pid.Pretty())
return pmes, nil
}
func (s *TextileService) handleThreadInvite(pid peer.ID, pmes *pb.Envelope, options interface{}) (*pb.Envelope, error) {
log.Debug("received THREAD_INVITE message")
signed, err := unpackMessage(pmes)
if err != nil {
return nil, err
}
invite := new(pb.ThreadInvite)
if err := proto.Unmarshal(signed.Block, invite); err != nil {
return nil, err
}
// load thread
threadId := libp2pc.ConfigEncodeKey(invite.Header.ThreadPk)
if _, thrd := s.getThread(threadId); thrd != nil {
// thread exists, aborting
return nil, nil
}
// check if it's meant for us (should be, but safety first)
if invite.InviteeId != s.self.Pretty() {
return nil, errors.New("invalid invite block")
}
// unknown thread and invite meant for us
// unpack new thread secret that should be encrypted with our key
skb, err := crypto.Decrypt(s.node.PrivateKey, invite.SkCipher)
if err != nil {
return nil, err
}
sk, err := libp2pc.UnmarshalPrivateKey(skb)
if err != nil {
return nil, err
}
// verify thread sig
if err := crypto.Verify(sk.GetPublic(), signed.Block, signed.ThreadSig); err != nil {
return nil, err
}
// add to local ipfs for later use when joining
pmesb, err := proto.Marshal(pmes)
if err != nil {
return nil, err
}
ci, err := util.PinData(s.node, bytes.NewReader(pmesb))
if err != nil {
return nil, err
}
id := ci.Hash().B58String()
// send notification
notification, err := buildNotification(sk, invite.Header, repo.ReceivedInviteNotification)
if err != nil {
return nil, err
}
notification.Subject = invite.SuggestedName
notification.SubjectId = libp2pc.ConfigEncodeKey(invite.Header.ThreadPk)
notification.BlockId = id // invite block
notification.Body = "invited you to join"
if err := s.notify(notification); err != nil {
return nil, err
}
return nil, nil
}
func (s *TextileService) handleThreadJoin(pid peer.ID, pmes *pb.Envelope, options interface{}) (*pb.Envelope, error) {
log.Debug("received THREAD_JOIN message")
signed, err := unpackMessage(pmes)
if err != nil {
return nil, err
}
join := new(pb.ThreadJoin)
if err := proto.Unmarshal(signed.Block, join); err != nil {
return nil, err
}
// load thread
threadId := libp2pc.ConfigEncodeKey(join.Header.ThreadPk)
_, thrd := s.getThread(threadId)
if thrd == nil {
return nil, errors.New("invalid join block")
}
// verify thread sig
if err := thrd.Verify(signed); err != nil {
return nil, err
}
// handle
addr, _, err := thrd.HandleJoinBlock(&pid, pmes, signed, join, false)
if err != nil {
return nil, err
}
// send notification
notification, err := buildNotification(thrd.PrivKey, join.Header, repo.PeerJoinedNotification)
if err != nil {
return nil, err
}
notification.Subject = thrd.Name
notification.SubjectId = thrd.Id
notification.BlockId = addr.B58String()
notification.Body = "joined"
if err := s.notify(notification); err != nil {
return nil, err
}
return nil, nil
}
func (s *TextileService) handleThreadLeave(pid peer.ID, pmes *pb.Envelope, options interface{}) (*pb.Envelope, error) {
log.Debug("received THREAD_LEAVE message")
signed, err := unpackMessage(pmes)
if err != nil {
return nil, err
}
leave := new(pb.ThreadLeave)
if err := proto.Unmarshal(signed.Block, leave); err != nil {
return nil, err
}
// load thread
threadId := libp2pc.ConfigEncodeKey(leave.Header.ThreadPk)
_, thrd := s.getThread(threadId)
if thrd == nil {
return nil, errors.New("invalid leave block")
}
// verify thread sig
if err := thrd.Verify(signed); err != nil {
return nil, err
}
// handle
addr, err := thrd.HandleLeaveBlock(&pid, pmes, signed, leave, false)
if err != nil {
return nil, err
}
// send notification
notification, err := buildNotification(thrd.PrivKey, leave.Header, repo.PeerLeftNotification)
if err != nil {
return nil, err
}
notification.Subject = thrd.Name
notification.SubjectId = thrd.Id
notification.BlockId = addr.B58String()
notification.Body = "left"
if err := s.notify(notification); err != nil {
return nil, err
}
return nil, nil
}
func (s *TextileService) handleThreadData(pid peer.ID, pmes *pb.Envelope, options interface{}) (*pb.Envelope, error) {
log.Debug("received THREAD_DATA message")
signed, err := unpackMessage(pmes)
if err != nil {
return nil, err
}
data := new(pb.ThreadData)
if err := proto.Unmarshal(signed.Block, data); err != nil {
return nil, err
}
// load thread
threadId := libp2pc.ConfigEncodeKey(data.Header.ThreadPk)
_, thrd := s.getThread(threadId)
if thrd == nil {
return nil, errors.New("invalid data block")
}
// verify thread sig
if err := thrd.Verify(signed); err != nil {
return nil, err
}
// handle
addr, err := thrd.HandleDataBlock(&pid, pmes, signed, data, false)
if err != nil {
return nil, err
}
// send notification
// check for old username format
if data.Header.AuthorUnCipher == nil {
data.Header.AuthorUnCipher = data.UsernameCipher
}
var notification *repo.Notification
switch data.Type {
case pb.ThreadData_PHOTO:
notification, err = buildNotification(thrd.PrivKey, data.Header, repo.PhotoAddedNotification)
if err != nil {
return nil, err
}
notification.DataId = data.DataId
notification.Body = "added a photo"
case pb.ThreadData_TEXT:
notification, err = buildNotification(thrd.PrivKey, data.Header, repo.TextAddedNotification)
if err != nil {
return nil, err
}
body, err := thrd.Decrypt(data.CaptionCipher)
if err != nil {
return nil, err
}
notification.Body = string(body)
}
notification.BlockId = addr.B58String()
notification.Subject = thrd.Name
notification.SubjectId = thrd.Id
if err := s.notify(notification); err != nil {
return nil, err
}
return nil, nil
}
func (s *TextileService) handleThreadAnnotation(pid peer.ID, pmes *pb.Envelope, options interface{}) (*pb.Envelope, error) {
log.Debug("received THREAD_ANNOTATION message")
signed, err := unpackMessage(pmes)
if err != nil {
return nil, err
}
annotation := new(pb.ThreadAnnotation)
if err := proto.Unmarshal(signed.Block, annotation); err != nil {
return nil, err
}
// load thread
threadId := libp2pc.ConfigEncodeKey(annotation.Header.ThreadPk)
_, thrd := s.getThread(threadId)
if thrd == nil {
return nil, errors.New("invalid annotation block")
}
// verify thread sig
if err := thrd.Verify(signed); err != nil {
return nil, err
}
// handle
addr, err := thrd.HandleAnnotationBlock(&pid, pmes, signed, annotation, false)
if err != nil {
return nil, err
}
// find dataId block locally
dataBlock := s.datastore.Blocks().Get(annotation.DataId)
if dataBlock == nil {
return nil, nil
}
var target string
authorId, err := util.IdFromEncodedPublicKey(dataBlock.AuthorPk)
if err != nil {
return nil, err
}
// NOTE: not restricted to photo annotations here, just currently only thing possible
if authorId.Pretty() == s.self.Pretty() {
target = "your photo"
} else {
target = "a photo"
}
// send notification
var notification *repo.Notification
switch annotation.Type {
case pb.ThreadAnnotation_COMMENT:
notification, err = buildNotification(thrd.PrivKey, annotation.Header, repo.CommentAddedNotification)
if err != nil {
return nil, err
}
body, err := thrd.Decrypt(annotation.CaptionCipher)
if err != nil {
return nil, err
}
notification.Body = fmt.Sprintf("commented on %s: \"%s\"", target, string(body))
case pb.ThreadAnnotation_LIKE:
notification, err = buildNotification(thrd.PrivKey, annotation.Header, repo.LikeAddedNotification)
if err != nil {
return nil, err
}
notification.Body = "liked " + target
}
notification.BlockId = addr.B58String()
notification.DataId = dataBlock.DataId
notification.Subject = thrd.Name
notification.SubjectId = thrd.Id
if err := s.notify(notification); err != nil {
return nil, err
}
return nil, nil
}
func (s *TextileService) handleThreadIgnore(pid peer.ID, pmes *pb.Envelope, options interface{}) (*pb.Envelope, error) {
log.Debug("received THREAD_IGNORE message")
signed, err := unpackMessage(pmes)
if err != nil {
return nil, err
}
ignore := new(pb.ThreadIgnore)
if err := proto.Unmarshal(signed.Block, ignore); err != nil {
return nil, err
}
// load thread
threadId := libp2pc.ConfigEncodeKey(ignore.Header.ThreadPk)
_, thrd := s.getThread(threadId)
if thrd == nil {
return nil, errors.New("invalid ignore block")
}
// verify thread sig
if err := thrd.Verify(signed); err != nil {
return nil, err
}
// handle
if _, err := thrd.HandleIgnoreBlock(&pid, pmes, signed, ignore, false); err != nil {
return nil, err
}
return nil, nil
}
func (s *TextileService) handleThreadMerge(pid peer.ID, pmes *pb.Envelope, options interface{}) (*pb.Envelope, error) {
log.Debug("received THREAD_MERGE message")
signed, err := unpackMessage(pmes)
if err != nil {
return nil, err
}
merge := new(pb.ThreadMerge)
if err := proto.Unmarshal(signed.Block, merge); err != nil {
return nil, err
}
// load thread
threadId := libp2pc.ConfigEncodeKey(merge.ThreadPk)
_, thrd := s.getThread(threadId)
if thrd == nil {
return nil, errors.New("invalid merge block")
}
// verify thread sig
if err := thrd.Verify(signed); err != nil {
return nil, err
}
// handle
if _, err := thrd.HandleMergeBlock(&pid, pmes.Message, signed, merge, false); err != nil {
return nil, err
}
return nil, nil
}
func (s *TextileService) handleOfflineAck(pid peer.ID, pmes *pb.Envelope, options interface{}) (*pb.Envelope, error) {
if pmes.Message.Payload == nil {
return nil, errors.New("payload is nil")
}
id, err := peer.IDB58Decode(string(pmes.Message.Payload.Value))
if err != nil {
return nil, err
}
pointer := s.datastore.Pointers().Get(id)
if pointer == nil {
return nil, errors.New("pointer not found")
}
if pointer.CancelId == nil || pointer.CancelId.Pretty() != pid.Pretty() {
return nil, errors.New("peer is not authorized to delete pointer")
}
if err := s.datastore.Pointers().Delete(id); err != nil {
return nil, err
}
log.Debugf("received OFFLINE_ACK message from %s", pid.Pretty())
return nil, nil
}
func (s *TextileService) handleOfflineRelay(pid peer.ID, pmes *pb.Envelope, options interface{}) (*pb.Envelope, error) {
if pmes.Message.Payload == nil {
return nil, errors.New("payload is nil")
}
plaintext, err := crypto.Decrypt(s.node.PrivateKey, pmes.Message.Payload.Value)
if err != nil {
return nil, err
}
// unmarshal plaintext
env := &pb.Envelope{}
err = proto.Unmarshal(plaintext, env)
if err != nil {
return nil, err
}
// validate envelope signature
ser, err := proto.Marshal(env.Message)
if err != nil {
return nil, err
}
pk, err := libp2pc.UnmarshalPublicKey(env.Pk)
if err != nil {
return nil, err
}
if err := crypto.Verify(pk, ser, env.Sig); err != nil {
return nil, err
}
id, err := peer.IDFromPublicKey(pk)
if err != nil {
return nil, err
}
// get handler for this message type
handler := s.HandlerForMsgType(env.Message.Type)
if handler == nil {
log.Debug("got back nil handler from HandlerForMsgType")
return nil, nil
}
// dispatch handler
_, err = handler(id, env, true)
if err != nil {
log.Errorf("handle message error: %s", err)
return nil, err
}
log.Debugf("received OFFLINE_RELAY message from %s", pid.Pretty())
return nil, nil
}
func (s *TextileService) handleBlock(pid peer.ID, pmes *pb.Envelope, options interface{}) (*pb.Envelope, error) {
if pmes.Message.Payload == nil {
return nil, errors.New("payload is nil")
}
pbblock := new(pb.Block)
err := ptypes.UnmarshalAny(pmes.Message.Payload, pbblock)
if err != nil {
return nil, err
}
id, err := cid.Decode(pbblock.Cid)
if err != nil {
return nil, err
}
block, err := blocks.NewBlockWithCid(pbblock.RawData, id)
if err != nil {
return nil, err
}
if err := s.node.Blocks.AddBlock(block); err != nil {
return nil, err
}
log.Debugf("received IPFS_BLOCK message from %s", pid.Pretty())
return nil, nil
}
func (s *TextileService) handleStore(pid peer.ID, pmes *pb.Envelope, options interface{}) (*pb.Envelope, error) {
errorResponse := func(error string) *pb.Message {
payload := &any.Any{Value: []byte(error)}
message := &pb.Message{
Type: pb.Message_ERROR,
Payload: payload,
}
return message
}
if pmes.Message.Payload == nil {
return nil, errors.New("payload is nil")
}
cList := new(pb.CidList)
err := ptypes.UnmarshalAny(pmes.Message.Payload, cList)
if err != nil {
return s.newEnvelope(errorResponse("could not unmarshall message"))
}
var need []string
for _, id := range cList.Cids {
decoded, err := cid.Decode(id)
if err != nil {
continue
}
has, err := s.node.Blockstore.Has(decoded)
if err != nil || !has {
need = append(need, decoded.String())
}
}
log.Debugf("received STORE message from %s", pid.Pretty())
log.Debugf("requesting %d blocks from %s", len(need), pid.Pretty())
resp := new(pb.CidList)
resp.Cids = need
payload, err := ptypes.MarshalAny(resp)
if err != nil {
return s.newEnvelope(errorResponse("error marshalling response"))
}
message := &pb.Message{
Type: pb.Message_STORE,
Payload: payload,
}
return s.newEnvelope(message)
}
func (s *TextileService) handleError(peer peer.ID, pmes *pb.Envelope, options interface{}) (*pb.Envelope, error) {
if pmes.Message.Payload == nil {
return nil, errors.New("payload is nil")
}
errorMessage := new(pb.Error)
err := ptypes.UnmarshalAny(pmes.Message.Payload, errorMessage)
if err != nil {
return nil, err
}
return nil, nil
}
func unpackMessage(pmes *pb.Envelope) (*pb.SignedThreadBlock, error) {
if pmes.Message.Payload == nil {
return nil, errors.New("payload is nil")
}
signed := new(pb.SignedThreadBlock)
if err := ptypes.UnmarshalAny(pmes.Message.Payload, signed); err != nil {
return nil, err
}
return signed, nil
}
func buildNotification(threadKey libp2pc.PrivKey, header *pb.ThreadBlockHeader, ntype repo.NotificationType) (*repo.Notification, error) {
date, err := ptypes.Timestamp(header.Date)
if err != nil {
return nil, err
}
authorPk, err := libp2pc.UnmarshalPublicKey(header.AuthorPk)
if err != nil {
return nil, err
}
authorId, err := peer.IDFromPublicKey(authorPk)
if err != nil {
return nil, err
}
var authorUn string
if header.AuthorUnCipher != nil {
authorUnb, err := crypto.Decrypt(threadKey, header.AuthorUnCipher)
if err != nil {
return nil, err
}
authorUn = string(authorUnb)
}
return &repo.Notification{
Id: ksuid.New().String(),
Date: date,
ActorId: authorId.Pretty(),
ActorUsername: authorUn,
Type: ntype,
}, nil
}