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