/
upload.go
767 lines (712 loc) · 21.8 KB
/
upload.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
// Copyright © 2019 yellowsea <hh1271941291@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package p2p
import (
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"strconv"
"sync"
"github.com/gogo/protobuf/proto"
"github.com/google/uuid"
p2pNet "github.com/libp2p/go-libp2p-core/network"
p2pPeer "github.com/libp2p/go-libp2p-core/peer"
"github.com/sirupsen/logrus"
tpCrypto "github.com/yellowssi/SeaStorage-TP/crypto"
tpUser "github.com/yellowssi/SeaStorage-TP/user"
"github.com/yellowssi/SeaStorage/crypto"
"github.com/yellowssi/SeaStorage/lib"
"github.com/yellowssi/SeaStorage/p2p/pb"
)
const (
uploadQueryRequest = "/SeaStorage/upload/queryreq/1.0.0"
uploadQueryResponse = "/SeaStorage/upload/queryres/1.0.0"
uploadRequest = "/SeaStorage/upload/request/1.0.0"
uploadResponse = "/SeaStorage/upload/response/1.0.0"
uploadOperation = "/SeaStorage/upload/operation/1.0.0"
)
/*
* Sea Upload Handler
*/
// seaUploadInfo is used for tag of upload
type seaUploadInfo struct {
sync.RWMutex
downloading int
size int64
hash string
}
// SeaUploadQueryProtocol provides listener for upload query request protobuf and sending upload query response protobuf.
type SeaUploadQueryProtocol struct {
node *SeaNode
}
// NewSeaUploadQueryProtocol is the construct for SeaUploadQueryProtocol.
func NewSeaUploadQueryProtocol(node *SeaNode) *SeaUploadQueryProtocol {
p := &SeaUploadQueryProtocol{
node: node,
}
node.SetStreamHandler(uploadQueryRequest, p.onUploadQueryRequest)
return p
}
// onUploadQueryRequest listen for upload query request protobuf.
func (p *SeaUploadQueryProtocol) onUploadQueryRequest(s p2pNet.Stream) {
data := &pb.UploadQueryRequest{}
buf, err := ioutil.ReadAll(s)
if err != nil {
s.Reset()
lib.Logger.Error(err)
return
}
s.Close()
err = proto.Unmarshal(buf, data)
if err != nil {
lib.Logger.Error(err)
return
}
lib.Logger.WithFields(logrus.Fields{
"type": "upload query request",
"from": s.Conn().RemotePeer().String(),
"tag": data.Tag,
"size": data.Size,
}).Info("received upload query request")
valid := p.node.authenticateMessage(data, data.MessageData)
if !valid {
lib.Logger.WithFields(logrus.Fields{
"type": "upload query request",
"from": s.Conn().RemotePeer().String(),
"tag": data.Tag,
"size": data.Size,
}).Warn("failed to authenticate message")
return
}
if _, err = os.Stat(path.Join(p.node.storagePath, tpCrypto.BytesToHex(data.MessageData.NodePubKey), "tmp")); os.IsNotExist(err) {
err = os.MkdirAll(path.Join(p.node.storagePath, tpCrypto.BytesToHex(data.MessageData.NodePubKey), "tmp"), 0700)
if err != nil {
lib.Logger.Error("failed to create directory:", path.Join(p.node.storagePath, tpCrypto.BytesToHex(data.MessageData.NodePubKey), "tmp"))
return
}
}
if _, err = os.Stat(path.Join(p.node.storagePath, tpCrypto.BytesToHex(data.MessageData.NodePubKey), "home")); os.IsNotExist(err) {
err = os.MkdirAll(path.Join(p.node.storagePath, tpCrypto.BytesToHex(data.MessageData.NodePubKey), "home"), 0700)
if err != nil {
lib.Logger.Error("failed to create directory:", path.Join(p.node.storagePath, tpCrypto.BytesToHex(data.MessageData.NodePubKey), "home"))
return
}
}
if _, err = os.Stat(path.Join(p.node.storagePath, tpCrypto.BytesToHex(data.MessageData.NodePubKey), "shared")); os.IsNotExist(err) {
err = os.MkdirAll(path.Join(p.node.storagePath, tpCrypto.BytesToHex(data.MessageData.NodePubKey), "shared"), 0700)
if err != nil {
lib.Logger.Error("failed to create directory:", path.Join(p.node.storagePath, tpCrypto.BytesToHex(data.MessageData.NodePubKey), "home"))
return
}
}
err = p.sendUploadQueryResponse(s.Conn().RemotePeer(), data.MessageData.Id, data.Tag, data.Size)
if err != nil {
lib.Logger.WithFields(logrus.Fields{
"type": "upload query response",
"to": s.Conn().RemotePeer().String(),
"tag": data.Tag,
}).Errorf("failed to sent: %v", err)
} else {
lib.Logger.WithFields(logrus.Fields{
"type": "upload query response",
"to": s.Conn().RemotePeer().String(),
"tag": data.Tag,
}).Info("sent success")
}
}
// sendUploadQueryResponse send upload query response protobuf.
func (p *SeaUploadQueryProtocol) sendUploadQueryResponse(peerID p2pPeer.ID, messageID, tag string, size int64) error {
resp := &pb.UploadQueryResponse{
MessageData: p.node.NewMessageData(messageID, false),
Tag: tag,
}
signature, err := p.node.signProtoMessage(resp)
if err != nil {
return fmt.Errorf("failed to sign protobuf: %v", err)
}
resp.MessageData.Sign = signature
ok := p.node.sendProtoMessage(peerID, uploadQueryResponse, resp)
if !ok {
return errors.New("failed to sent proto message")
}
p.node.uploadInfos.Lock()
uploadInfos, ok := p.node.uploadInfos.m[peerID]
if !ok {
p.node.uploadInfos.m[peerID] = map[string]*seaUploadInfo{tag: {size: size}}
} else {
uploadInfos[tag] = &seaUploadInfo{size: size}
}
p.node.uploadInfos.Unlock()
return nil
}
// SeaUploadProtocol provides listener for upload request protobuf and sending upload response protobuf.
type SeaUploadProtocol struct {
node *SeaNode
}
// NewSeaUploadProtocol is the construct for SeaUploadProtocol.
func NewSeaUploadProtocol(node *SeaNode) *SeaUploadProtocol {
p := &SeaUploadProtocol{
node: node,
}
node.SetStreamHandler(uploadRequest, p.onUploadRequest)
return p
}
// onUploadRequest listen for upload request protobuf.
func (p *SeaUploadProtocol) onUploadRequest(s p2pNet.Stream) {
data := &pb.UploadRequest{}
buf, err := ioutil.ReadAll(s)
if err != nil {
s.Reset()
lib.Logger.Error(err)
return
}
s.Close()
err = proto.Unmarshal(buf, data)
if err != nil {
lib.Logger.Error(err)
return
}
lib.Logger.WithFields(logrus.Fields{
"type": "upload request",
"from": s.Conn().RemotePeer().String(),
"tag": data.Tag,
}).Info("received protobuf")
valid := p.node.authenticateMessage(data, data.MessageData)
if !valid {
lib.Logger.WithFields(logrus.Fields{
"type": "upload request",
"from": s.Conn().RemotePeer().String(),
"tag": data.Tag,
}).Warn("failed to authenticate message")
return
}
p.node.uploadInfos.Lock()
uploadInfoMap, ok := p.node.uploadInfos.m[s.Conn().RemotePeer()]
p.node.uploadInfos.Unlock()
if !ok {
lib.Logger.WithFields(logrus.Fields{
"type": "upload request",
"from": s.Conn().RemotePeer().String(),
"tag": data.Tag,
}).Warn("invalid protobuf")
return
}
p.node.uploadInfos.Lock()
uploadInfo, ok := uploadInfoMap[data.Tag]
p.node.uploadInfos.Unlock()
if !ok {
lib.Logger.WithFields(logrus.Fields{
"type": "upload request",
"from": s.Conn().RemotePeer().String(),
"tag": data.Tag,
}).Warn("invalid protobuf")
return
}
if len(data.Data) == 0 {
done := make(chan bool)
go func() {
for {
if uploadInfo.downloading == 0 {
done <- true
return
}
}
}()
<-done
// Verify fragments
storagePath := path.Join(p.node.storagePath, tpCrypto.BytesToHex(data.MessageData.NodePubKey), "tmp")
targetFile := path.Join(storagePath, data.Tag)
f, err := os.OpenFile(targetFile, os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
lib.Logger.Error("failed to create file:", targetFile)
return
}
for i := int64(0); i < data.PackageId; i++ {
fragment, err := ioutil.ReadFile(path.Join(storagePath, data.Tag+"-"+strconv.FormatInt(i, 10)))
if err != nil {
if os.IsNotExist(err) {
err = p.sendUploadResponse(s.Conn().RemotePeer(), data.MessageData.Id, data.Tag, "", i)
if err != nil {
lib.Logger.WithFields(logrus.Fields{
"type": "upload response",
"to": s.Conn().RemotePeer().String(),
"tag": data.Tag,
"packageId": i,
}).Errorf("failed to sent: %v", err)
} else {
lib.Logger.WithFields(logrus.Fields{
"type": "upload response",
"to": s.Conn().RemotePeer().String(),
"tag": data.Tag,
"packageId": i,
}).Info("sent success")
}
} else {
lib.Logger.Error("failed to read fragment:", path.Join(storagePath, data.Tag+"-"+strconv.FormatInt(i, 10)))
}
return
}
_, err = f.WriteAt(fragment, lib.PackageSize*i)
if err != nil {
lib.Logger.WithFields(logrus.Fields{
"peer": s.Conn().RemotePeer().String(),
"tag": data.Tag,
}).Error("failed to merge fragment")
return
}
}
for i := int64(0); i < data.PackageId; i++ {
os.Remove(path.Join(storagePath, data.Tag+"-"+strconv.FormatInt(i, 10)))
}
err = f.Truncate(uploadInfo.size)
f.Close()
if err != nil {
lib.Logger.Errorf("failed to truncate file: %s", targetFile)
os.Remove(targetFile)
return
}
// Calculate the pubHash of file
f, err = os.Open(targetFile)
if err != nil {
lib.Logger.Errorf("failed to open file: %s", targetFile)
return
}
defer f.Close()
hash, err := crypto.CalFileHash(f)
if err != nil {
lib.Logger.Errorf("failed to calculate file pubHash: %s", targetFile)
return
}
err = p.sendUploadResponse(s.Conn().RemotePeer(), data.MessageData.Id, data.Tag, hash, data.PackageId)
if err == nil {
lib.Logger.WithFields(logrus.Fields{
"type": "upload response",
"to": s.Conn().RemotePeer().String(),
"tag": data.Tag,
}).Info("sent success")
uploadInfo.hash = hash
} else {
lib.Logger.WithFields(logrus.Fields{
"type": "upload response",
"to": s.Conn().RemotePeer().String(),
"tag": data.Tag,
}).Error("failed to sent protobuf")
// TODO: clean failed file
}
} else {
uploadInfo.Lock()
uploadInfo.downloading++
uploadInfo.Unlock()
filename := path.Join(p.node.storagePath, tpCrypto.BytesToHex(data.MessageData.NodePubKey), "tmp", data.Tag+"-"+strconv.FormatInt(data.PackageId, 10))
f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
lib.Logger.Error("failed to create fragment:", err)
s.Reset()
}
_, err = f.WriteAt(data.Data, 0)
if err != nil {
lib.Logger.Error("failed to write data to file:", filename)
}
uploadInfo.Lock()
uploadInfo.downloading--
uploadInfo.Unlock()
}
}
// sendUploadResponse send upload response protobuf.
func (p *SeaUploadProtocol) sendUploadResponse(peerID p2pPeer.ID, messageID, tag, hash string, id int64) error {
resp := &pb.UploadResponse{
MessageData: p.node.NewMessageData(messageID, true),
Tag: tag,
PackageId: id,
Hash: hash,
}
signature, err := p.node.signProtoMessage(resp)
if err != nil {
return fmt.Errorf("failed to sign proto message: %v", err)
}
resp.MessageData.Sign = signature
ok := p.node.sendProtoMessage(peerID, uploadResponse, resp)
if ok {
return nil
}
return errors.New("failed to sent upload response")
}
// SeaOperationProtocol provides listener for operation request protobuf.
type SeaOperationProtocol struct {
node *SeaNode
}
// NewSeaOperationProtocol is the construct for SeaOperationProtocol.
func NewSeaOperationProtocol(node *SeaNode) *SeaOperationProtocol {
p := &SeaOperationProtocol{
node: node,
}
node.SetStreamHandler(uploadOperation, p.onOperationRequest)
return p
}
// onOperationRequest listen for operation request protobuf.
func (p *SeaOperationProtocol) onOperationRequest(s p2pNet.Stream) {
data := &pb.OperationRequest{}
buf, err := ioutil.ReadAll(s)
if err != nil {
s.Reset()
lib.Logger.Error(err)
return
}
s.Close()
err = proto.Unmarshal(buf, data)
if err != nil {
lib.Logger.Error(err)
return
}
lib.Logger.WithFields(logrus.Fields{
"type": "operation request",
"from": s.Conn().RemotePeer().String(),
"tag": data.Tag,
}).Info("received operation request")
valid := p.node.authenticateMessage(data, data.MessageData)
if !valid {
lib.Logger.WithFields(logrus.Fields{
"type": "operation request",
"from": s.Conn().RemotePeer().String(),
"tag": data.Tag,
}).Warn("failed to authenticate message")
return
}
p.node.uploadInfos.Lock()
uploadInfo, ok := p.node.uploadInfos.m[s.Conn().RemotePeer()][data.Tag]
p.node.uploadInfos.Unlock()
if !ok {
lib.Logger.WithFields(logrus.Fields{
"type": "operation request",
"from": s.Conn().RemotePeer().String(),
"tag": data.Tag,
}).Warn("invalid operation")
return
}
op, err := tpUser.OperationFromBytes(data.Operation)
if err != nil {
lib.Logger.WithFields(logrus.Fields{
"type": "operation request",
"from": s.Conn().RemotePeer().String(),
"tag": data.Tag,
}).Warn("failed to unmarshal:", err)
return
}
if !op.Verify() || op.PublicKey != tpCrypto.BytesToHex(data.MessageData.NodePubKey) || op.Hash != uploadInfo.hash {
lib.Logger.WithFields(logrus.Fields{
"type": "operation request",
"from": s.Conn().RemotePeer().String(),
"tag": data.Tag,
}).Warn("invalid operation")
return
}
peerPub := tpCrypto.BytesToHex(data.MessageData.NodePubKey)
err = os.Rename(path.Join(p.node.storagePath, peerPub, "tmp", data.Tag), path.Join(p.node.storagePath, peerPub, "home", op.Hash))
if err != nil {
lib.Logger.WithFields(logrus.Fields{
"type": "operation request",
"from": s.Conn().RemotePeer().String(),
"tag": data.Tag,
}).Warn("failed to rename file:", err)
return
}
p.node.operations.Lock()
p.node.operations.m[tpCrypto.SHA512HexFromBytes(op.ToBytes())] = *op
p.node.operations.Unlock()
p.node.uploadInfos.Lock()
delete(p.node.uploadInfos.m[s.Conn().RemotePeer()], data.Tag)
p.node.uploadInfos.Unlock()
}
/*
* User Upload Handler
*/
// userUploadInfo is used for tag of upload file
type userUploadInfo struct {
sync.RWMutex
src *os.File
packages int64
operations map[p2pPeer.ID]*tpUser.Operation
done chan bool
}
// UserUploadQueryProtocol provides sending upload query request protobuf.
type UserUploadQueryProtocol struct {
node *UserNode
}
// NewUserUploadQueryProtocol is the construct for UserUploadQueryProtocol.
func NewUserUploadQueryProtocol(node *UserNode) *UserUploadQueryProtocol {
p := &UserUploadQueryProtocol{
node: node,
}
node.SetStreamHandler(uploadQueryResponse, p.onUploadQueryResponse)
return p
}
// onUploadQueryResponse listen for upload query response protobuf.
func (p *UserUploadQueryProtocol) onUploadQueryResponse(s p2pNet.Stream) {
data := &pb.UploadQueryResponse{}
buf, err := ioutil.ReadAll(s)
if err != nil {
s.Reset()
lib.Logger.Error(err)
return
}
s.Close()
err = proto.Unmarshal(buf, data)
if err != nil {
lib.Logger.Error(err)
return
}
lib.Logger.WithFields(logrus.Fields{
"type": "upload query response",
"from": s.Conn().RemotePeer().String(),
"tag": data.Tag,
}).Info("received upload query response")
valid := p.node.authenticateMessage(data, data.MessageData)
if !valid {
lib.Logger.WithFields(logrus.Fields{
"type": "upload query response",
"from": s.Conn().RemotePeer().String(),
"tag": data.Tag,
}).Warn("failed to authenticate message")
return
}
p.node.sendUpload(s.Conn().RemotePeer(), data.MessageData.Id, data.Tag)
}
// SendUploadQuery send upload query protobuf.
func (p *UserUploadQueryProtocol) SendUploadQuery(peerID p2pPeer.ID, tag string, size int64) error {
req := &pb.UploadQueryRequest{
MessageData: p.node.NewMessageData(uuid.New().String(), true),
Tag: tag,
Size: size,
}
signature, err := p.node.signProtoMessage(req)
if err != nil {
return err
}
req.MessageData.Sign = signature
ok := p.node.sendProtoMessage(peerID, uploadQueryRequest, req)
if !ok {
return errors.New("send proto message failed")
}
return nil
}
// UserUploadProtocol provides sending upload request protobuf and listener for upload response protobuf.
type UserUploadProtocol struct {
node *UserNode
}
// NewUserUploadProtocol is the construct for UserUploadProtocol.
func NewUserUploadProtocol(node *UserNode) *UserUploadProtocol {
p := &UserUploadProtocol{
node: node,
}
node.SetStreamHandler(uploadResponse, p.onUploadResponse)
return p
}
// onUploadResponse listen for upload response protobuf.
func (p *UserUploadProtocol) onUploadResponse(s p2pNet.Stream) {
data := &pb.UploadResponse{}
buf, err := ioutil.ReadAll(s)
if err != nil {
s.Reset()
lib.Logger.Error(err)
return
}
s.Close()
err = proto.Unmarshal(buf, data)
if err != nil {
lib.Logger.Error(err)
return
}
lib.Logger.WithFields(logrus.Fields{
"type": "upload response",
"from": s.Conn().RemotePeer().String(),
"tag": data.Tag,
}).Info("received upload response")
valid := p.node.authenticateMessage(data, data.MessageData)
if !valid {
lib.Logger.WithFields(logrus.Fields{
"type": "upload response",
"from": s.Conn().RemotePeer().String(),
"tag": data.Tag,
}).Warn("failed to authenticate message")
return
}
p.node.uploadInfos.Lock()
uploadInfo, ok := p.node.uploadInfos.m[data.Tag]
p.node.uploadInfos.Unlock()
if ok {
if data.PackageId < uploadInfo.packages {
err := p.node.sendPackage(s.Conn().RemotePeer(), data.MessageData.Id, data.Tag, data.PackageId)
if err != nil {
lib.Logger.WithFields(logrus.Fields{
"type": "upload request",
"to": s.Conn().RemotePeer().String(),
"tag": data.Tag,
"packageId": data.PackageId,
}).Errorf("failed to send protobuf: %v", err)
return
}
lib.Logger.WithFields(logrus.Fields{
"type": "upload request",
"to": s.Conn().RemotePeer().String(),
"tag": data.Tag,
"packageId": data.PackageId,
}).Info("sent success")
err = p.node.sendPackage(s.Conn().RemotePeer(), data.MessageData.Id, data.Tag, uploadInfo.packages)
if err != nil {
lib.Logger.WithFields(logrus.Fields{
"type": "upload request",
"to": s.Conn().RemotePeer().String(),
"tag": data.Tag,
"packageId": uploadInfo.packages,
}).Warn("failed to send upload request")
return
}
lib.Logger.WithFields(logrus.Fields{
"type": "upload response",
"from": s.Conn().RemotePeer().String(),
"tag": data.Tag,
"packageId": uploadInfo.packages,
}).Info("sent success")
return
} else if data.PackageId == uploadInfo.packages {
uploadInfo.Lock()
operation, ok := uploadInfo.operations[s.Conn().RemotePeer()]
uploadInfo.Unlock()
if ok && data.Hash == operation.Hash {
err = p.node.sendOperationProtocol(s.Conn().RemotePeer(), data.MessageData.Id, data.Tag)
if err != nil {
lib.Logger.WithFields(logrus.Fields{
"type": "operation request",
"to": s.Conn().RemotePeer().String(),
"tag": data.Tag,
}).Errorf("failed to send protobuf: %v", err)
}
uploadInfo.Lock()
delete(uploadInfo.operations, s.Conn().RemotePeer())
length := len(uploadInfo.operations)
uploadInfo.Unlock()
if length == 0 {
uploadInfo.done <- true
}
return
}
}
}
lib.Logger.WithFields(logrus.Fields{
"type": "upload response",
"from": s.Conn().RemotePeer().String(),
"tag": data.Tag,
"hash": data.Hash,
}).Warn("invalid protobuf")
}
// sendUpload send packages of file.
func (p *UserUploadProtocol) sendUpload(peerID p2pPeer.ID, messageID, tag string) {
p.node.uploadInfos.Lock()
uploadInfo, ok := p.node.uploadInfos.m[tag]
p.node.uploadInfos.Unlock()
if !ok {
lib.Logger.WithFields(logrus.Fields{
"from": peerID.String(),
"tag": tag,
}).Warn("invalid upload query response")
return
}
for i := int64(0); i <= uploadInfo.packages; i++ {
err := p.node.sendPackage(peerID, messageID, tag, i)
if err != nil {
err = p.node.sendPackage(peerID, messageID, tag, i)
if err != nil {
lib.Logger.WithFields(logrus.Fields{
"to": peerID.String(),
"tag": tag,
"package": i,
}).Warn("failed to sent package")
}
}
}
}
// sendPackage send upload request protobuf.
func (p *UserUploadProtocol) sendPackage(peerID p2pPeer.ID, messageID, tag string, id int64) error {
var req *pb.UploadRequest
p.node.uploadInfos.Lock()
uploadInfo := p.node.uploadInfos.m[tag]
p.node.uploadInfos.Unlock()
if id == uploadInfo.packages {
req = &pb.UploadRequest{
MessageData: p.node.NewMessageData(messageID, true),
PackageId: id,
Tag: tag,
Data: nil,
}
} else {
buf := make([]byte, lib.PackageSize)
n, err := uploadInfo.src.ReadAt(buf, id*lib.PackageSize)
if err != nil && err != io.EOF {
return err
}
req = &pb.UploadRequest{
MessageData: p.node.NewMessageData(messageID, true),
PackageId: id,
Tag: tag,
Data: buf[:n],
}
}
signature, err := p.node.signProtoMessage(req)
if err != nil {
return fmt.Errorf("failed to sign proto message: %v", err)
}
req.MessageData.Sign = signature
ok := p.node.sendProtoMessage(peerID, uploadRequest, req)
if ok {
return nil
}
return errors.New("failed to send proto message")
}
// UserOperationProtocol provides sending operation request protobuf.
type UserOperationProtocol struct {
node *UserNode
}
// NewUserOperationProtocol is the construct for UserOperationProtocol.
func NewUserOperationProtocol(n *UserNode) *UserOperationProtocol {
return &UserOperationProtocol{
node: n,
}
}
// sendOperationProtocol send operation request and delete upload info of the tag.
func (p *UserOperationProtocol) sendOperationProtocol(peerID p2pPeer.ID, messageID, tag string) error {
p.node.uploadInfos.Lock()
uploadInfoMap := p.node.uploadInfos.m[tag]
p.node.uploadInfos.Unlock()
uploadInfoMap.Lock()
operation := uploadInfoMap.operations[peerID]
uploadInfoMap.Unlock()
op := &pb.OperationRequest{
MessageData: p.node.NewMessageData(messageID, true),
Tag: tag,
Operation: operation.ToBytes(),
}
signature, err := p.node.signProtoMessage(op)
if err != nil {
return err
}
op.MessageData.Sign = signature
ok := p.node.sendProtoMessage(peerID, uploadOperation, op)
if !ok {
return errors.New("failed to send proto message")
}
return nil
}