api.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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 api
  16. import (
  17. "context"
  18. "embed"
  19. "fmt"
  20. "io/fs"
  21. "net"
  22. "net/http"
  23. "strings"
  24. "time"
  25. "github.com/libp2p/go-libp2p-core/network"
  26. "github.com/libp2p/go-libp2p-core/peer"
  27. "github.com/miekg/dns"
  28. apiTypes "github.com/mudler/edgevpn/api/types"
  29. "github.com/labstack/echo/v4"
  30. "github.com/mudler/edgevpn/pkg/node"
  31. "github.com/mudler/edgevpn/pkg/protocol"
  32. "github.com/mudler/edgevpn/pkg/services"
  33. "github.com/mudler/edgevpn/pkg/types"
  34. )
  35. //go:embed public
  36. var embededFiles embed.FS
  37. func getFileSystem() http.FileSystem {
  38. fsys, err := fs.Sub(embededFiles, "public")
  39. if err != nil {
  40. panic(err)
  41. }
  42. return http.FS(fsys)
  43. }
  44. const (
  45. MachineURL = "/api/machines"
  46. UsersURL = "/api/users"
  47. ServiceURL = "/api/services"
  48. BlockchainURL = "/api/blockchain"
  49. LedgerURL = "/api/ledger"
  50. SummaryURL = "/api/summary"
  51. FileURL = "/api/files"
  52. NodesURL = "/api/nodes"
  53. DNSURL = "/api/dns"
  54. PeerstoreURL = "/api/peerstore"
  55. )
  56. func API(ctx context.Context, l string, defaultInterval, timeout time.Duration, e *node.Node) error {
  57. ledger, _ := e.Ledger()
  58. ec := echo.New()
  59. if strings.HasPrefix(l, "unix://") {
  60. unixListener, err := net.Listen("unix", strings.ReplaceAll(l, "unix://", ""))
  61. if err != nil {
  62. return err
  63. }
  64. ec.Listener = unixListener
  65. }
  66. assetHandler := http.FileServer(getFileSystem())
  67. // Get data from ledger
  68. ec.GET(FileURL, func(c echo.Context) error {
  69. list := []*types.File{}
  70. for _, v := range ledger.CurrentData()[protocol.FilesLedgerKey] {
  71. machine := &types.File{}
  72. v.Unmarshal(machine)
  73. list = append(list, machine)
  74. }
  75. return c.JSON(http.StatusOK, list)
  76. })
  77. ec.GET(SummaryURL, func(c echo.Context) error {
  78. files := len(ledger.CurrentData()[protocol.FilesLedgerKey])
  79. machines := len(ledger.CurrentData()[protocol.MachinesLedgerKey])
  80. users := len(ledger.CurrentData()[protocol.UsersLedgerKey])
  81. services := len(ledger.CurrentData()[protocol.ServicesLedgerKey])
  82. onChainNodes := len(e.HubRoom.Topic.ListPeers())
  83. p2pPeers := len(e.Host().Network().Peerstore().Peers())
  84. nodeID := e.Host().ID().String()
  85. blockchain := ledger.Index()
  86. return c.JSON(http.StatusOK, types.Summary{
  87. Files: files,
  88. Machines: machines,
  89. Users: users,
  90. Services: services,
  91. BlockChain: blockchain,
  92. OnChainNodes: onChainNodes,
  93. Peers: p2pPeers,
  94. NodeID: nodeID,
  95. })
  96. })
  97. ec.GET(MachineURL, func(c echo.Context) error {
  98. list := []*apiTypes.Machine{}
  99. for _, v := range ledger.CurrentData()[protocol.MachinesLedgerKey] {
  100. machine := &types.Machine{}
  101. v.Unmarshal(machine)
  102. m := &apiTypes.Machine{Machine: *machine}
  103. if e.Host().Network().Connectedness(peer.ID(machine.PeerID)) == network.Connected {
  104. m.Connected = true
  105. }
  106. for _, p := range e.HubRoom.Topic.ListPeers() {
  107. if p.String() == machine.PeerID {
  108. m.OnChain = true
  109. }
  110. }
  111. list = append(list, m)
  112. }
  113. return c.JSON(http.StatusOK, list)
  114. })
  115. ec.GET(NodesURL, func(c echo.Context) error {
  116. list := []apiTypes.Peer{}
  117. for _, v := range e.HubRoom.Topic.ListPeers() {
  118. list = append(list, apiTypes.Peer{ID: v.String()})
  119. }
  120. return c.JSON(http.StatusOK, list)
  121. })
  122. ec.GET(PeerstoreURL, func(c echo.Context) error {
  123. list := []apiTypes.Peer{}
  124. for _, v := range e.Host().Network().Peerstore().Peers() {
  125. list = append(list, apiTypes.Peer{ID: v.String()})
  126. }
  127. e.HubRoom.Topic.ListPeers()
  128. return c.JSON(http.StatusOK, list)
  129. })
  130. ec.GET(UsersURL, func(c echo.Context) error {
  131. user := []*types.User{}
  132. for _, v := range ledger.CurrentData()[protocol.UsersLedgerKey] {
  133. u := &types.User{}
  134. v.Unmarshal(u)
  135. user = append(user, u)
  136. }
  137. return c.JSON(http.StatusOK, user)
  138. })
  139. ec.GET(ServiceURL, func(c echo.Context) error {
  140. list := []*types.Service{}
  141. for _, v := range ledger.CurrentData()[protocol.ServicesLedgerKey] {
  142. srvc := &types.Service{}
  143. v.Unmarshal(srvc)
  144. list = append(list, srvc)
  145. }
  146. return c.JSON(http.StatusOK, list)
  147. })
  148. ec.GET("/*", echo.WrapHandler(http.StripPrefix("/", assetHandler)))
  149. ec.GET(BlockchainURL, func(c echo.Context) error {
  150. return c.JSON(http.StatusOK, ledger.LastBlock())
  151. })
  152. ec.GET(LedgerURL, func(c echo.Context) error {
  153. return c.JSON(http.StatusOK, ledger.CurrentData())
  154. })
  155. ec.GET(fmt.Sprintf("%s/:bucket/:key", LedgerURL), func(c echo.Context) error {
  156. bucket := c.Param("bucket")
  157. key := c.Param("key")
  158. return c.JSON(http.StatusOK, ledger.CurrentData()[bucket][key])
  159. })
  160. ec.GET(fmt.Sprintf("%s/:bucket", LedgerURL), func(c echo.Context) error {
  161. bucket := c.Param("bucket")
  162. return c.JSON(http.StatusOK, ledger.CurrentData()[bucket])
  163. })
  164. announcing := struct{ State string }{"Announcing"}
  165. // Store arbitrary data
  166. ec.PUT(fmt.Sprintf("%s/:bucket/:key/:value", LedgerURL), func(c echo.Context) error {
  167. bucket := c.Param("bucket")
  168. key := c.Param("key")
  169. value := c.Param("value")
  170. ledger.Persist(context.Background(), defaultInterval, timeout, bucket, key, value)
  171. return c.JSON(http.StatusOK, announcing)
  172. })
  173. ec.GET(DNSURL, func(c echo.Context) error {
  174. res := []apiTypes.DNS{}
  175. for r, e := range ledger.CurrentData()[protocol.DNSKey] {
  176. var t types.DNS
  177. e.Unmarshal(&t)
  178. d := map[string]string{}
  179. for k, v := range t {
  180. d[dns.TypeToString[uint16(k)]] = v
  181. }
  182. res = append(res,
  183. apiTypes.DNS{
  184. Regex: r,
  185. Records: d,
  186. })
  187. }
  188. return c.JSON(http.StatusOK, res)
  189. })
  190. // Announce dns
  191. ec.POST(DNSURL, func(c echo.Context) error {
  192. d := new(apiTypes.DNS)
  193. if err := c.Bind(d); err != nil {
  194. return echo.NewHTTPError(http.StatusBadRequest, err.Error())
  195. }
  196. entry := make(types.DNS)
  197. for r, e := range d.Records {
  198. entry[dns.Type(dns.StringToType[r])] = e
  199. }
  200. services.PersistDNSRecord(context.Background(), ledger, defaultInterval, timeout, d.Regex, entry)
  201. return c.JSON(http.StatusOK, announcing)
  202. })
  203. // Delete data from ledger
  204. ec.DELETE(fmt.Sprintf("%s/:bucket", LedgerURL), func(c echo.Context) error {
  205. bucket := c.Param("bucket")
  206. ledger.AnnounceDeleteBucket(context.Background(), defaultInterval, timeout, bucket)
  207. return c.JSON(http.StatusOK, announcing)
  208. })
  209. ec.DELETE(fmt.Sprintf("%s/:bucket/:key", LedgerURL), func(c echo.Context) error {
  210. bucket := c.Param("bucket")
  211. key := c.Param("key")
  212. ledger.AnnounceDeleteBucketKey(context.Background(), defaultInterval, timeout, bucket, key)
  213. return c.JSON(http.StatusOK, announcing)
  214. })
  215. ec.HideBanner = true
  216. if err := ec.Start(l); err != nil && err != http.ErrServerClosed {
  217. return err
  218. }
  219. go func() {
  220. <-ctx.Done()
  221. ct, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  222. ec.Shutdown(ct)
  223. cancel()
  224. }()
  225. return nil
  226. }