files.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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/node"
  23. "github.com/mudler/edgevpn/pkg/protocol"
  24. "github.com/libp2p/go-libp2p-core/network"
  25. "github.com/libp2p/go-libp2p-core/peer"
  26. "github.com/mudler/edgevpn/pkg/blockchain"
  27. "github.com/mudler/edgevpn/pkg/types"
  28. "github.com/pkg/errors"
  29. )
  30. // ShareFile shares a file to the p2p network.
  31. // meant to be called before a node is started with Start()
  32. func ShareFile(ctx context.Context, ledger *blockchain.Ledger, n *node.Node, l log.StandardLogger, announcetime time.Duration, fileID, filepath string) error {
  33. _, err := os.Stat(filepath)
  34. if err != nil {
  35. return err
  36. }
  37. l.Infof("Serving '%s' as '%s'", filepath, fileID)
  38. n.AddNetworkService(func(ctx context.Context, c node.Config, n *node.Node, b *blockchain.Ledger) error {
  39. // By announcing periodically our service to the blockchain
  40. ledger.Announce(
  41. ctx,
  42. announcetime,
  43. func() {
  44. // Retrieve current ID for ip in the blockchain
  45. existingValue, found := ledger.GetKey(protocol.FilesLedgerKey, fileID)
  46. service := &types.Service{}
  47. existingValue.Unmarshal(service)
  48. // If mismatch, update the blockchain
  49. if !found || service.PeerID != n.Host().ID().String() {
  50. updatedMap := map[string]interface{}{}
  51. updatedMap[fileID] = types.File{PeerID: n.Host().ID().String(), Name: fileID}
  52. ledger.Add(protocol.FilesLedgerKey, updatedMap)
  53. }
  54. },
  55. )
  56. return nil
  57. })
  58. // 2) Set a stream handler
  59. // which connect to the given address/Port and Send what we receive from the Stream.
  60. n.AddStreamHandler(protocol.FileProtocol, func(stream network.Stream) {
  61. go func() {
  62. l.Infof("(file %s) Received connection from %s", fileID, stream.Conn().RemotePeer().String())
  63. // Retrieve current ID for ip in the blockchain
  64. _, found := ledger.GetKey(protocol.UsersLedgerKey, stream.Conn().RemotePeer().String())
  65. // If mismatch, update the blockchain
  66. if !found {
  67. l.Info("Reset", stream.Conn().RemotePeer().String(), "Not found in the ledger")
  68. stream.Reset()
  69. return
  70. }
  71. f, err := os.Open(filepath)
  72. if err != nil {
  73. return
  74. }
  75. io.Copy(stream, f)
  76. f.Close()
  77. stream.Close()
  78. l.Infof("(file %s) Done handling %s", fileID, stream.Conn().RemotePeer().String())
  79. }()
  80. })
  81. return nil
  82. }
  83. func ReceiveFile(ctx context.Context, ledger *blockchain.Ledger, n *node.Node, l log.StandardLogger, announcetime time.Duration, fileID string, path string) error {
  84. // Announce ourselves so nodes accepts our connection
  85. ledger.Announce(
  86. ctx,
  87. announcetime,
  88. func() {
  89. // Retrieve current ID for ip in the blockchain
  90. _, found := ledger.GetKey(protocol.UsersLedgerKey, n.Host().ID().String())
  91. // If mismatch, update the blockchain
  92. if !found {
  93. updatedMap := map[string]interface{}{}
  94. updatedMap[n.Host().ID().String()] = &types.User{
  95. PeerID: n.Host().ID().String(),
  96. Timestamp: time.Now().String(),
  97. }
  98. ledger.Add(protocol.UsersLedgerKey, updatedMap)
  99. }
  100. },
  101. )
  102. for {
  103. select {
  104. case <-ctx.Done():
  105. return errors.New("context canceled")
  106. default:
  107. time.Sleep(5 * time.Second)
  108. l.Debug("Attempting to find file in the blockchain")
  109. _, found := ledger.GetKey(protocol.UsersLedgerKey, n.Host().ID().String())
  110. if !found {
  111. continue
  112. }
  113. existingValue, found := ledger.GetKey(protocol.FilesLedgerKey, fileID)
  114. fi := &types.File{}
  115. existingValue.Unmarshal(fi)
  116. // If mismatch, update the blockchain
  117. if !found {
  118. l.Debug("file not found on blockchain, retrying in 5 seconds")
  119. continue
  120. } else {
  121. // Retrieve current ID for ip in the blockchain
  122. existingValue, found := ledger.GetKey(protocol.FilesLedgerKey, fileID)
  123. fi := &types.File{}
  124. existingValue.Unmarshal(fi)
  125. // If mismatch, update the blockchain
  126. if !found {
  127. return errors.New("file not found")
  128. }
  129. // Decode the Peer
  130. d, err := peer.Decode(fi.PeerID)
  131. if err != nil {
  132. return err
  133. }
  134. // Open a stream
  135. stream, err := n.Host().NewStream(context.Background(), d, protocol.FileProtocol.ID())
  136. if err != nil {
  137. l.Debugf("failed to dial %s, retrying in 5 seconds", d)
  138. continue
  139. }
  140. l.Infof("Saving file %s to %s", fileID, path)
  141. f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
  142. if err != nil {
  143. return err
  144. }
  145. io.Copy(f, stream)
  146. f.Close()
  147. l.Infof("Received file %s to %s", fileID, path)
  148. return nil
  149. }
  150. }
  151. }
  152. }