vpn.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. /*
  2. Copyright © 2021-2022 Ettore Di Giacinto <[email protected]>
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package vpn
  14. import (
  15. "context"
  16. "fmt"
  17. "io"
  18. "net"
  19. "os"
  20. "runtime"
  21. "sync"
  22. "time"
  23. "github.com/ipfs/go-log"
  24. "github.com/libp2p/go-libp2p/core/network"
  25. "github.com/libp2p/go-libp2p/core/peer"
  26. "github.com/google/gopacket"
  27. "github.com/google/gopacket/layers"
  28. "github.com/mudler/edgevpn/internal"
  29. "github.com/mudler/edgevpn/pkg/blockchain"
  30. "github.com/mudler/edgevpn/pkg/logger"
  31. "github.com/mudler/edgevpn/pkg/node"
  32. "github.com/mudler/edgevpn/pkg/protocol"
  33. "github.com/mudler/edgevpn/pkg/stream"
  34. "github.com/mudler/edgevpn/pkg/types"
  35. "github.com/mudler/water"
  36. "github.com/pkg/errors"
  37. "github.com/songgao/packets/ethernet"
  38. )
  39. type streamManager interface {
  40. Connected(n network.Network, c network.Stream)
  41. Disconnected(n network.Network, c network.Stream)
  42. HasStream(n network.Network, pid peer.ID) (network.Stream, error)
  43. Close() error
  44. }
  45. func VPNNetworkService(p ...Option) node.NetworkService {
  46. return func(ctx context.Context, nc node.Config, n *node.Node, b *blockchain.Ledger) error {
  47. c := &Config{
  48. Concurrency: 1,
  49. LedgerAnnounceTime: 5 * time.Second,
  50. Timeout: 15 * time.Second,
  51. Logger: logger.New(log.LevelDebug),
  52. MaxStreams: 30,
  53. }
  54. if err := c.Apply(p...); err != nil {
  55. return err
  56. }
  57. ifce, err := createInterface(c)
  58. if err != nil {
  59. return err
  60. }
  61. defer ifce.Close()
  62. var mgr streamManager
  63. if !c.lowProfile {
  64. // Create stream manager for outgoing connections
  65. mgr, err = stream.NewConnManager(10, c.MaxStreams)
  66. if err != nil {
  67. return err
  68. }
  69. // Attach it to the same context
  70. go func() {
  71. <-ctx.Done()
  72. mgr.Close()
  73. }()
  74. }
  75. // Set stream handler during runtime
  76. n.Host().SetStreamHandler(protocol.EdgeVPN.ID(), streamHandler(b, ifce, c))
  77. // Announce our IP
  78. ip, _, err := net.ParseCIDR(c.InterfaceAddress)
  79. if err != nil {
  80. return err
  81. }
  82. b.Announce(
  83. ctx,
  84. c.LedgerAnnounceTime,
  85. func() {
  86. machine := &types.Machine{}
  87. // Retrieve current ID for ip in the blockchain
  88. existingValue, found := b.GetKey(protocol.MachinesLedgerKey, ip.String())
  89. existingValue.Unmarshal(machine)
  90. // If mismatch, update the blockchain
  91. if !found || machine.PeerID != n.Host().ID().String() {
  92. updatedMap := map[string]interface{}{}
  93. updatedMap[ip.String()] = newBlockChainData(n, ip.String())
  94. b.Add(protocol.MachinesLedgerKey, updatedMap)
  95. }
  96. },
  97. )
  98. if c.NetLinkBootstrap {
  99. if err := prepareInterface(c); err != nil {
  100. return err
  101. }
  102. }
  103. // read packets from the interface
  104. return readPackets(ctx, mgr, c, n, b, ifce)
  105. }
  106. }
  107. // Start the node and the vpn. Returns an error in case of failure
  108. // When starting the vpn, there is no need to start the node
  109. func Register(p ...Option) ([]node.Option, error) {
  110. return []node.Option{node.WithNetworkService(VPNNetworkService(p...))}, nil
  111. }
  112. func streamHandler(l *blockchain.Ledger, ifce *water.Interface, c *Config) func(stream network.Stream) {
  113. return func(stream network.Stream) {
  114. if !l.Exists(protocol.MachinesLedgerKey,
  115. func(d blockchain.Data) bool {
  116. machine := &types.Machine{}
  117. d.Unmarshal(machine)
  118. return machine.PeerID == stream.Conn().RemotePeer().String()
  119. }) {
  120. stream.Reset()
  121. return
  122. }
  123. _, err := io.Copy(ifce.ReadWriteCloser, stream)
  124. if err != nil {
  125. stream.Reset()
  126. }
  127. if c.lowProfile {
  128. stream.Close()
  129. }
  130. }
  131. }
  132. func newBlockChainData(n *node.Node, address string) types.Machine {
  133. hostname, _ := os.Hostname()
  134. return types.Machine{
  135. PeerID: n.Host().ID().String(),
  136. Hostname: hostname,
  137. OS: runtime.GOOS,
  138. Arch: runtime.GOARCH,
  139. Version: internal.Version,
  140. Address: address,
  141. }
  142. }
  143. func getFrame(ifce *water.Interface, c *Config) (ethernet.Frame, error) {
  144. var frame ethernet.Frame
  145. frame.Resize(c.MTU)
  146. n, err := ifce.Read([]byte(frame))
  147. if err != nil {
  148. return frame, errors.Wrap(err, "could not read from interface")
  149. }
  150. frame = frame[:n]
  151. return frame, nil
  152. }
  153. func handleFrame(mgr streamManager, frame ethernet.Frame, c *Config, n *node.Node, ip net.IP, ledger *blockchain.Ledger, ifce *water.Interface) error {
  154. ctx, cancel := context.WithTimeout(context.Background(), c.Timeout)
  155. defer cancel()
  156. var dstIP, srcIP net.IP
  157. var packet layers.IPv4
  158. if err := packet.DecodeFromBytes(frame, gopacket.NilDecodeFeedback); err != nil {
  159. var packet layers.IPv6
  160. if err := packet.DecodeFromBytes(frame, gopacket.NilDecodeFeedback); err != nil {
  161. return errors.Wrap(err, "could not parse header from frame")
  162. } else {
  163. dstIP = packet.DstIP
  164. srcIP = packet.SrcIP
  165. }
  166. } else {
  167. dstIP = packet.DstIP
  168. srcIP = packet.SrcIP
  169. }
  170. dst := dstIP.String()
  171. if c.RouterAddress != "" && srcIP.Equal(ip) {
  172. if _, found := ledger.GetKey(protocol.MachinesLedgerKey, dst); !found {
  173. dst = c.RouterAddress
  174. }
  175. }
  176. // Query the routing table
  177. value, found := ledger.GetKey(protocol.MachinesLedgerKey, dst)
  178. if !found {
  179. return fmt.Errorf("'%s' not found in the routing table", dst)
  180. }
  181. machine := &types.Machine{}
  182. value.Unmarshal(machine)
  183. // Decode the Peer
  184. d, err := peer.Decode(machine.PeerID)
  185. if err != nil {
  186. return errors.Wrap(err, "could not decode peer")
  187. }
  188. var stream network.Stream
  189. if mgr != nil {
  190. // Open a stream if necessary
  191. stream, err = mgr.HasStream(n.Host().Network(), d)
  192. if err == nil {
  193. _, err = stream.Write(frame)
  194. if err == nil {
  195. return nil
  196. }
  197. mgr.Disconnected(n.Host().Network(), stream)
  198. }
  199. }
  200. stream, err = n.Host().NewStream(ctx, d, protocol.EdgeVPN.ID())
  201. if err != nil {
  202. return fmt.Errorf("could not open stream to %s: %w", d.String(), err)
  203. }
  204. if mgr != nil {
  205. mgr.Connected(n.Host().Network(), stream)
  206. }
  207. _, err = stream.Write(frame)
  208. if c.lowProfile {
  209. return stream.Close()
  210. }
  211. return err
  212. }
  213. func connectionWorker(
  214. p chan ethernet.Frame,
  215. mgr streamManager,
  216. c *Config,
  217. n *node.Node,
  218. ip net.IP,
  219. wg *sync.WaitGroup,
  220. ledger *blockchain.Ledger,
  221. ifce *water.Interface) {
  222. defer wg.Done()
  223. for f := range p {
  224. if err := handleFrame(mgr, f, c, n, ip, ledger, ifce); err != nil {
  225. c.Logger.Debugf("could not handle frame: %s", err.Error())
  226. }
  227. }
  228. }
  229. // redirects packets from the interface to the node using the routing table in the blockchain
  230. func readPackets(ctx context.Context, mgr streamManager, c *Config, n *node.Node, ledger *blockchain.Ledger, ifce *water.Interface) error {
  231. ip, _, err := net.ParseCIDR(c.InterfaceAddress)
  232. if err != nil {
  233. return err
  234. }
  235. wg := new(sync.WaitGroup)
  236. packets := make(chan ethernet.Frame, c.ChannelBufferSize)
  237. defer func() {
  238. close(packets)
  239. wg.Wait()
  240. }()
  241. for i := 0; i < c.Concurrency; i++ {
  242. wg.Add(1)
  243. go connectionWorker(packets, mgr, c, n, ip, wg, ledger, ifce)
  244. }
  245. for {
  246. select {
  247. case <-ctx.Done():
  248. return nil
  249. default:
  250. frame, err := getFrame(ifce, c)
  251. if err != nil {
  252. c.Logger.Errorf("could not get frame '%s'", err.Error())
  253. continue
  254. }
  255. packets <- frame
  256. }
  257. }
  258. }