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