files.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. // Copyright © 2021-2022 Ettore Di Giacinto <[email protected]>
  2. //
  3. // This program is free software; you can redistribute it and/or modify
  4. // it under the terms of the GNU General Public License as published by
  5. // the Free Software Foundation; either version 2 of the License, or
  6. // (at your option) any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program; if not, see <http://www.gnu.org/licenses/>.
  15. package services
  16. import (
  17. "context"
  18. "io"
  19. "os"
  20. "time"
  21. "github.com/ipfs/go-log"
  22. "github.com/mudler/edgevpn/pkg/protocol"
  23. "github.com/libp2p/go-libp2p-core/network"
  24. "github.com/libp2p/go-libp2p-core/peer"
  25. "github.com/mudler/edgevpn/pkg/blockchain"
  26. "github.com/mudler/edgevpn/pkg/types"
  27. "github.com/pkg/errors"
  28. )
  29. func ShareFile(ctx context.Context, ledger *blockchain.Ledger, node types.Node, l log.StandardLogger, announcetime time.Duration, fileID, filepath string) error {
  30. _, err := os.Stat(filepath)
  31. if err != nil {
  32. return err
  33. }
  34. l.Infof("Serving '%s' as '%s'", filepath, fileID)
  35. // By announcing periodically our service to the blockchain
  36. ledger.Announce(
  37. ctx,
  38. announcetime,
  39. func() {
  40. // Retrieve current ID for ip in the blockchain
  41. existingValue, found := ledger.GetKey(protocol.FilesLedgerKey, fileID)
  42. service := &types.Service{}
  43. existingValue.Unmarshal(service)
  44. // If mismatch, update the blockchain
  45. if !found || service.PeerID != node.Host().ID().String() {
  46. updatedMap := map[string]interface{}{}
  47. updatedMap[fileID] = types.File{PeerID: node.Host().ID().String(), Name: fileID}
  48. ledger.Add(protocol.FilesLedgerKey, updatedMap)
  49. }
  50. },
  51. )
  52. // 2) Set a stream handler
  53. // which connect to the given address/Port and Send what we receive from the Stream.
  54. node.AddStreamHandler(protocol.FileProtocol, func(stream network.Stream) {
  55. go func() {
  56. l.Infof("(file %s) Received connection from %s", fileID, stream.Conn().RemotePeer().String())
  57. // Retrieve current ID for ip in the blockchain
  58. _, found := ledger.GetKey(protocol.UsersLedgerKey, stream.Conn().RemotePeer().String())
  59. // If mismatch, update the blockchain
  60. if !found {
  61. l.Info("Reset", stream.Conn().RemotePeer().String(), "Not found in the ledger")
  62. stream.Reset()
  63. return
  64. }
  65. f, err := os.Open(filepath)
  66. if err != nil {
  67. return
  68. }
  69. io.Copy(stream, f)
  70. f.Close()
  71. stream.Close()
  72. l.Infof("(file %s) Done handling %s", fileID, stream.Conn().RemotePeer().String())
  73. }()
  74. })
  75. return nil
  76. }
  77. func ReceiveFile(ctx context.Context, ledger *blockchain.Ledger, node types.Node, l log.StandardLogger, announcetime time.Duration, fileID string, path string) error {
  78. // Announce ourselves so nodes accepts our connection
  79. ledger.Announce(
  80. ctx,
  81. announcetime,
  82. func() {
  83. // Retrieve current ID for ip in the blockchain
  84. _, found := ledger.GetKey(protocol.UsersLedgerKey, node.Host().ID().String())
  85. // If mismatch, update the blockchain
  86. if !found {
  87. updatedMap := map[string]interface{}{}
  88. updatedMap[node.Host().ID().String()] = &types.User{
  89. PeerID: node.Host().ID().String(),
  90. Timestamp: time.Now().String(),
  91. }
  92. ledger.Add(protocol.UsersLedgerKey, updatedMap)
  93. }
  94. },
  95. )
  96. for {
  97. select {
  98. case <-ctx.Done():
  99. return errors.New("context canceled")
  100. default:
  101. time.Sleep(5 * time.Second)
  102. l.Debug("Attempting to find file in the blockchain")
  103. _, found := ledger.GetKey(protocol.UsersLedgerKey, node.Host().ID().String())
  104. if !found {
  105. continue
  106. }
  107. existingValue, found := ledger.GetKey(protocol.FilesLedgerKey, fileID)
  108. fi := &types.File{}
  109. existingValue.Unmarshal(fi)
  110. // If mismatch, update the blockchain
  111. if !found {
  112. l.Debug("file not found on blockchain, retrying in 5 seconds")
  113. continue
  114. } else {
  115. // Retrieve current ID for ip in the blockchain
  116. existingValue, found := ledger.GetKey(protocol.FilesLedgerKey, fileID)
  117. fi := &types.File{}
  118. existingValue.Unmarshal(fi)
  119. // If mismatch, update the blockchain
  120. if !found {
  121. return errors.New("file not found")
  122. }
  123. // Decode the Peer
  124. d, err := peer.Decode(fi.PeerID)
  125. if err != nil {
  126. return err
  127. }
  128. // Open a stream
  129. stream, err := node.Host().NewStream(context.Background(), d, protocol.FileProtocol.ID())
  130. if err != nil {
  131. l.Debugf("failed to dial %s, retrying in 5 seconds", d)
  132. continue
  133. }
  134. l.Infof("Saving file %s to %s", fileID, path)
  135. f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
  136. if err != nil {
  137. return err
  138. }
  139. io.Copy(f, stream)
  140. f.Close()
  141. l.Infof("Received file %s to %s", fileID, path)
  142. return nil
  143. }
  144. }
  145. }
  146. }