hosts.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. package logic
  2. import (
  3. "crypto/md5"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "os"
  8. "sort"
  9. "sync"
  10. "github.com/google/uuid"
  11. "golang.org/x/crypto/bcrypt"
  12. "golang.org/x/exp/slog"
  13. "github.com/gravitl/netmaker/database"
  14. "github.com/gravitl/netmaker/logger"
  15. "github.com/gravitl/netmaker/models"
  16. "github.com/gravitl/netmaker/servercfg"
  17. "github.com/gravitl/netmaker/utils"
  18. )
  19. var (
  20. hostCacheMutex = &sync.RWMutex{}
  21. hostsCacheMap = make(map[string]models.Host)
  22. )
  23. var (
  24. // ErrHostExists error indicating that host exists when trying to create new host
  25. ErrHostExists error = errors.New("host already exists")
  26. // ErrInvalidHostID
  27. ErrInvalidHostID error = errors.New("invalid host id")
  28. )
  29. var GetHostLocInfo = func(ip, token string) string { return "" }
  30. func getHostsFromCache() (hosts []models.Host) {
  31. hostCacheMutex.RLock()
  32. for _, host := range hostsCacheMap {
  33. hosts = append(hosts, host)
  34. }
  35. hostCacheMutex.RUnlock()
  36. return
  37. }
  38. func getHostsMapFromCache() (hostsMap map[string]models.Host) {
  39. hostCacheMutex.RLock()
  40. hostsMap = hostsCacheMap
  41. hostCacheMutex.RUnlock()
  42. return
  43. }
  44. func getHostFromCache(hostID string) (host models.Host, ok bool) {
  45. hostCacheMutex.RLock()
  46. host, ok = hostsCacheMap[hostID]
  47. hostCacheMutex.RUnlock()
  48. return
  49. }
  50. func storeHostInCache(h models.Host) {
  51. hostCacheMutex.Lock()
  52. hostsCacheMap[h.ID.String()] = h
  53. hostCacheMutex.Unlock()
  54. }
  55. func deleteHostFromCache(hostID string) {
  56. hostCacheMutex.Lock()
  57. delete(hostsCacheMap, hostID)
  58. hostCacheMutex.Unlock()
  59. }
  60. func loadHostsIntoCache(hMap map[string]models.Host) {
  61. hostCacheMutex.Lock()
  62. hostsCacheMap = hMap
  63. hostCacheMutex.Unlock()
  64. }
  65. const (
  66. maxPort = 1<<16 - 1
  67. minPort = 1025
  68. )
  69. // GetAllHosts - returns all hosts in flat list or error
  70. func GetAllHosts() ([]models.Host, error) {
  71. var currHosts []models.Host
  72. if servercfg.CacheEnabled() {
  73. currHosts := getHostsFromCache()
  74. if len(currHosts) != 0 {
  75. return currHosts, nil
  76. }
  77. }
  78. records, err := database.FetchRecords(database.HOSTS_TABLE_NAME)
  79. if err != nil && !database.IsEmptyRecord(err) {
  80. return nil, err
  81. }
  82. currHostsMap := make(map[string]models.Host)
  83. if servercfg.CacheEnabled() {
  84. defer loadHostsIntoCache(currHostsMap)
  85. }
  86. for k := range records {
  87. var h models.Host
  88. err = json.Unmarshal([]byte(records[k]), &h)
  89. if err != nil {
  90. return nil, err
  91. }
  92. currHosts = append(currHosts, h)
  93. currHostsMap[h.ID.String()] = h
  94. }
  95. return currHosts, nil
  96. }
  97. // GetAllHostsWithStatus - returns all hosts with at least one
  98. // node with given status.
  99. func GetAllHostsWithStatus(status models.NodeStatus) ([]models.Host, error) {
  100. hosts, err := GetAllHosts()
  101. if err != nil {
  102. return nil, err
  103. }
  104. var validHosts []models.Host
  105. for _, host := range hosts {
  106. if len(host.Nodes) == 0 {
  107. continue
  108. }
  109. nodes := GetHostNodes(&host)
  110. for _, node := range nodes {
  111. getNodeCheckInStatus(&node, false)
  112. if node.Status == status {
  113. validHosts = append(validHosts, host)
  114. break
  115. }
  116. }
  117. }
  118. return validHosts, nil
  119. }
  120. // GetAllHostsAPI - get's all the hosts in an API usable format
  121. func GetAllHostsAPI(hosts []models.Host) []models.ApiHost {
  122. apiHosts := []models.ApiHost{}
  123. for i := range hosts {
  124. newApiHost := hosts[i].ConvertNMHostToAPI()
  125. apiHosts = append(apiHosts, *newApiHost)
  126. }
  127. return apiHosts[:]
  128. }
  129. // GetHostsMap - gets all the current hosts on machine in a map
  130. func GetHostsMap() (map[string]models.Host, error) {
  131. if servercfg.CacheEnabled() {
  132. hostsMap := getHostsMapFromCache()
  133. if len(hostsMap) != 0 {
  134. return hostsMap, nil
  135. }
  136. }
  137. records, err := database.FetchRecords(database.HOSTS_TABLE_NAME)
  138. if err != nil && !database.IsEmptyRecord(err) {
  139. return nil, err
  140. }
  141. currHostMap := make(map[string]models.Host)
  142. if servercfg.CacheEnabled() {
  143. defer loadHostsIntoCache(currHostMap)
  144. }
  145. for k := range records {
  146. var h models.Host
  147. err = json.Unmarshal([]byte(records[k]), &h)
  148. if err != nil {
  149. return nil, err
  150. }
  151. currHostMap[h.ID.String()] = h
  152. }
  153. return currHostMap, nil
  154. }
  155. func DoesHostExistinTheNetworkAlready(h *models.Host, network models.NetworkID) bool {
  156. if len(h.Nodes) > 0 {
  157. for _, nodeID := range h.Nodes {
  158. node, err := GetNodeByID(nodeID)
  159. if err == nil && node.Network == network.String() {
  160. return true
  161. }
  162. }
  163. }
  164. return false
  165. }
  166. // GetHost - gets a host from db given id
  167. func GetHost(hostid string) (*models.Host, error) {
  168. if servercfg.CacheEnabled() {
  169. if host, ok := getHostFromCache(hostid); ok {
  170. return &host, nil
  171. }
  172. }
  173. record, err := database.FetchRecord(database.HOSTS_TABLE_NAME, hostid)
  174. if err != nil {
  175. return nil, err
  176. }
  177. var h models.Host
  178. if err = json.Unmarshal([]byte(record), &h); err != nil {
  179. return nil, err
  180. }
  181. if servercfg.CacheEnabled() {
  182. storeHostInCache(h)
  183. }
  184. return &h, nil
  185. }
  186. // GetHostByPubKey - gets a host from db given pubkey
  187. func GetHostByPubKey(hostPubKey string) (*models.Host, error) {
  188. hosts, err := GetAllHosts()
  189. if err != nil {
  190. return nil, err
  191. }
  192. for _, host := range hosts {
  193. if host.PublicKey.String() == hostPubKey {
  194. return &host, nil
  195. }
  196. }
  197. return nil, errors.New("host not found")
  198. }
  199. // CreateHost - creates a host if not exist
  200. func CreateHost(h *models.Host) error {
  201. hosts, hErr := GetAllHosts()
  202. clients, cErr := GetAllExtClients()
  203. if (hErr != nil && !database.IsEmptyRecord(hErr)) ||
  204. (cErr != nil && !database.IsEmptyRecord(cErr)) ||
  205. len(hosts)+len(clients) >= MachinesLimit {
  206. return errors.New("free tier limits exceeded on machines")
  207. }
  208. _, err := GetHost(h.ID.String())
  209. if (err != nil && !database.IsEmptyRecord(err)) || (err == nil) {
  210. return ErrHostExists
  211. }
  212. // encrypt that password so we never see it
  213. hash, err := bcrypt.GenerateFromPassword([]byte(h.HostPass), 5)
  214. if err != nil {
  215. return err
  216. }
  217. h.HostPass = string(hash)
  218. h.AutoUpdate = AutoUpdateEnabled()
  219. if GetServerSettings().ManageDNS {
  220. h.DNS = "yes"
  221. } else {
  222. h.DNS = "no"
  223. }
  224. if h.EndpointIP != nil {
  225. h.Location = GetHostLocInfo(h.EndpointIP.String(), os.Getenv("IP_INFO_TOKEN"))
  226. } else if h.EndpointIPv6 != nil {
  227. h.Location = GetHostLocInfo(h.EndpointIPv6.String(), os.Getenv("IP_INFO_TOKEN"))
  228. }
  229. checkForZombieHosts(h)
  230. return UpsertHost(h)
  231. }
  232. // UpdateHost - updates host data by field
  233. func UpdateHost(newHost, currentHost *models.Host) {
  234. // unchangeable fields via API here
  235. newHost.DaemonInstalled = currentHost.DaemonInstalled
  236. newHost.OS = currentHost.OS
  237. newHost.IPForwarding = currentHost.IPForwarding
  238. newHost.HostPass = currentHost.HostPass
  239. newHost.MacAddress = currentHost.MacAddress
  240. newHost.Debug = currentHost.Debug
  241. newHost.Nodes = currentHost.Nodes
  242. newHost.PublicKey = currentHost.PublicKey
  243. newHost.TrafficKeyPublic = currentHost.TrafficKeyPublic
  244. // changeable fields
  245. if len(newHost.Version) == 0 {
  246. newHost.Version = currentHost.Version
  247. }
  248. if len(newHost.Name) == 0 {
  249. newHost.Name = currentHost.Name
  250. }
  251. if newHost.MTU == 0 {
  252. newHost.MTU = currentHost.MTU
  253. }
  254. if newHost.ListenPort == 0 {
  255. newHost.ListenPort = currentHost.ListenPort
  256. }
  257. if newHost.PersistentKeepalive == 0 {
  258. newHost.PersistentKeepalive = currentHost.PersistentKeepalive
  259. }
  260. }
  261. // UpdateHostFromClient - used for updating host on server with update recieved from client
  262. func UpdateHostFromClient(newHost, currHost *models.Host) (sendPeerUpdate bool) {
  263. if newHost.PublicKey != currHost.PublicKey {
  264. currHost.PublicKey = newHost.PublicKey
  265. sendPeerUpdate = true
  266. }
  267. if newHost.ListenPort != 0 && currHost.ListenPort != newHost.ListenPort {
  268. currHost.ListenPort = newHost.ListenPort
  269. sendPeerUpdate = true
  270. }
  271. if newHost.WgPublicListenPort != 0 &&
  272. currHost.WgPublicListenPort != newHost.WgPublicListenPort {
  273. currHost.WgPublicListenPort = newHost.WgPublicListenPort
  274. sendPeerUpdate = true
  275. }
  276. isEndpointChanged := false
  277. if !currHost.EndpointIP.Equal(newHost.EndpointIP) {
  278. currHost.EndpointIP = newHost.EndpointIP
  279. sendPeerUpdate = true
  280. isEndpointChanged = true
  281. }
  282. if !currHost.EndpointIPv6.Equal(newHost.EndpointIPv6) {
  283. currHost.EndpointIPv6 = newHost.EndpointIPv6
  284. sendPeerUpdate = true
  285. isEndpointChanged = true
  286. }
  287. for i := range newHost.Interfaces {
  288. newHost.Interfaces[i].AddressString = newHost.Interfaces[i].Address.String()
  289. }
  290. utils.SortIfacesByName(currHost.Interfaces)
  291. utils.SortIfacesByName(newHost.Interfaces)
  292. if !utils.CompareIfaces(currHost.Interfaces, newHost.Interfaces) {
  293. currHost.Interfaces = newHost.Interfaces
  294. sendPeerUpdate = true
  295. }
  296. if isEndpointChanged {
  297. for _, nodeID := range currHost.Nodes {
  298. node, err := GetNodeByID(nodeID)
  299. if err != nil {
  300. slog.Error("failed to get node:", "id", node.ID, "error", err)
  301. continue
  302. }
  303. if node.FailedOverBy != uuid.Nil {
  304. ResetFailedOverPeer(&node)
  305. }
  306. }
  307. }
  308. currHost.DaemonInstalled = newHost.DaemonInstalled
  309. currHost.Debug = newHost.Debug
  310. currHost.Verbosity = newHost.Verbosity
  311. currHost.Version = newHost.Version
  312. currHost.IsStaticPort = newHost.IsStaticPort
  313. currHost.IsStatic = newHost.IsStatic
  314. currHost.MTU = newHost.MTU
  315. currHost.Name = newHost.Name
  316. if len(newHost.NatType) > 0 && newHost.NatType != currHost.NatType {
  317. currHost.NatType = newHost.NatType
  318. sendPeerUpdate = true
  319. }
  320. return
  321. }
  322. // UpsertHost - upserts into DB a given host model, does not check for existence*
  323. func UpsertHost(h *models.Host) error {
  324. data, err := json.Marshal(h)
  325. if err != nil {
  326. return err
  327. }
  328. err = database.Insert(h.ID.String(), string(data), database.HOSTS_TABLE_NAME)
  329. if err != nil {
  330. return err
  331. }
  332. if servercfg.CacheEnabled() {
  333. storeHostInCache(*h)
  334. }
  335. return nil
  336. }
  337. // RemoveHost - removes a given host from server
  338. func RemoveHost(h *models.Host, forceDelete bool) error {
  339. if !forceDelete && len(h.Nodes) > 0 {
  340. return fmt.Errorf("host still has associated nodes")
  341. }
  342. if len(h.Nodes) > 0 {
  343. if err := DisassociateAllNodesFromHost(h.ID.String()); err != nil {
  344. return err
  345. }
  346. }
  347. err := database.DeleteRecord(database.HOSTS_TABLE_NAME, h.ID.String())
  348. if err != nil {
  349. return err
  350. }
  351. if servercfg.CacheEnabled() {
  352. deleteHostFromCache(h.ID.String())
  353. }
  354. go func() {
  355. if servercfg.IsDNSMode() {
  356. SetDNS()
  357. }
  358. }()
  359. return nil
  360. }
  361. // RemoveHostByID - removes a given host by id from server
  362. func RemoveHostByID(hostID string) error {
  363. err := database.DeleteRecord(database.HOSTS_TABLE_NAME, hostID)
  364. if err != nil {
  365. return err
  366. }
  367. if servercfg.CacheEnabled() {
  368. deleteHostFromCache(hostID)
  369. }
  370. return nil
  371. }
  372. // UpdateHostNetwork - adds/deletes host from a network
  373. func UpdateHostNetwork(h *models.Host, network string, add bool) (*models.Node, error) {
  374. for _, nodeID := range h.Nodes {
  375. node, err := GetNodeByID(nodeID)
  376. if err != nil || node.PendingDelete {
  377. continue
  378. }
  379. if node.Network == network {
  380. if !add {
  381. return &node, nil
  382. } else {
  383. return &node, errors.New("host already part of network " + network)
  384. }
  385. }
  386. }
  387. if !add {
  388. return nil, errors.New("host not part of the network " + network)
  389. } else {
  390. newNode := models.Node{}
  391. newNode.Server = servercfg.GetServer()
  392. newNode.Network = network
  393. newNode.HostID = h.ID
  394. if err := AssociateNodeToHost(&newNode, h); err != nil {
  395. return nil, err
  396. }
  397. return &newNode, nil
  398. }
  399. }
  400. // AssociateNodeToHost - associates and creates a node with a given host
  401. // should be the only way nodes get created as of 0.18
  402. func AssociateNodeToHost(n *models.Node, h *models.Host) error {
  403. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  404. return ErrInvalidHostID
  405. }
  406. n.HostID = h.ID
  407. err := createNode(n)
  408. if err != nil {
  409. return err
  410. }
  411. currentHost, err := GetHost(h.ID.String())
  412. if err != nil {
  413. return err
  414. }
  415. h.HostPass = currentHost.HostPass
  416. h.Nodes = append(currentHost.Nodes, n.ID.String())
  417. return UpsertHost(h)
  418. }
  419. // DissasociateNodeFromHost - deletes a node and removes from host nodes
  420. // should be the only way nodes are deleted as of 0.18
  421. func DissasociateNodeFromHost(n *models.Node, h *models.Host) error {
  422. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  423. return ErrInvalidHostID
  424. }
  425. if n.HostID != h.ID { // check if node actually belongs to host
  426. return fmt.Errorf("node is not associated with host")
  427. }
  428. if len(h.Nodes) == 0 {
  429. return fmt.Errorf("no nodes present in given host")
  430. }
  431. nList := []string{}
  432. for i := range h.Nodes {
  433. if h.Nodes[i] != n.ID.String() {
  434. nList = append(nList, h.Nodes[i])
  435. }
  436. }
  437. h.Nodes = nList
  438. go func() {
  439. if servercfg.IsPro {
  440. if clients, err := GetNetworkExtClients(n.Network); err != nil {
  441. for i := range clients {
  442. AllowClientNodeAccess(&clients[i], n.ID.String())
  443. }
  444. }
  445. }
  446. }()
  447. if err := DeleteNodeByID(n); err != nil {
  448. return err
  449. }
  450. return UpsertHost(h)
  451. }
  452. // DisassociateAllNodesFromHost - deletes all nodes of the host
  453. func DisassociateAllNodesFromHost(hostID string) error {
  454. host, err := GetHost(hostID)
  455. if err != nil {
  456. return err
  457. }
  458. for _, nodeID := range host.Nodes {
  459. node, err := GetNodeByID(nodeID)
  460. if err != nil {
  461. logger.Log(0, "failed to get host node, node id:", nodeID, err.Error())
  462. continue
  463. }
  464. if err := DeleteNode(&node, true); err != nil {
  465. logger.Log(0, "failed to delete node", node.ID.String(), err.Error())
  466. continue
  467. }
  468. logger.Log(3, "deleted node", node.ID.String(), "of host", host.ID.String())
  469. }
  470. host.Nodes = []string{}
  471. return UpsertHost(host)
  472. }
  473. // GetDefaultHosts - retrieve all hosts marked as default from DB
  474. func GetDefaultHosts() []models.Host {
  475. defaultHostList := []models.Host{}
  476. hosts, err := GetAllHosts()
  477. if err != nil {
  478. return defaultHostList
  479. }
  480. for i := range hosts {
  481. if hosts[i].IsDefault {
  482. defaultHostList = append(defaultHostList, hosts[i])
  483. }
  484. }
  485. return defaultHostList[:]
  486. }
  487. // GetHostNetworks - fetches all the networks
  488. func GetHostNetworks(hostID string) []string {
  489. currHost, err := GetHost(hostID)
  490. if err != nil {
  491. return nil
  492. }
  493. nets := []string{}
  494. for i := range currHost.Nodes {
  495. n, err := GetNodeByID(currHost.Nodes[i])
  496. if err != nil {
  497. return nil
  498. }
  499. nets = append(nets, n.Network)
  500. }
  501. return nets
  502. }
  503. // GetRelatedHosts - fetches related hosts of a given host
  504. func GetRelatedHosts(hostID string) []models.Host {
  505. relatedHosts := []models.Host{}
  506. networks := GetHostNetworks(hostID)
  507. networkMap := make(map[string]struct{})
  508. for _, network := range networks {
  509. networkMap[network] = struct{}{}
  510. }
  511. hosts, err := GetAllHosts()
  512. if err == nil {
  513. for _, host := range hosts {
  514. if host.ID.String() == hostID {
  515. continue
  516. }
  517. networks := GetHostNetworks(host.ID.String())
  518. for _, network := range networks {
  519. if _, ok := networkMap[network]; ok {
  520. relatedHosts = append(relatedHosts, host)
  521. break
  522. }
  523. }
  524. }
  525. }
  526. return relatedHosts
  527. }
  528. // CheckHostPort checks host endpoints to ensures that hosts on the same server
  529. // with the same endpoint have different listen ports
  530. // in the case of 64535 hosts or more with same endpoint, ports will not be changed
  531. func CheckHostPorts(h *models.Host) (changed bool) {
  532. portsInUse := make(map[int]bool, 0)
  533. hosts, err := GetAllHosts()
  534. if err != nil {
  535. return
  536. }
  537. originalPort := h.ListenPort
  538. defer func() {
  539. if originalPort != h.ListenPort {
  540. changed = true
  541. }
  542. }()
  543. if h.EndpointIP == nil {
  544. return
  545. }
  546. for _, host := range hosts {
  547. if host.ID.String() == h.ID.String() {
  548. // skip self
  549. continue
  550. }
  551. if host.EndpointIP == nil {
  552. continue
  553. }
  554. if !host.EndpointIP.Equal(h.EndpointIP) {
  555. continue
  556. }
  557. portsInUse[host.ListenPort] = true
  558. }
  559. // iterate until port is not found or max iteration is reached
  560. for i := 0; portsInUse[h.ListenPort] && i < maxPort-minPort+1; i++ {
  561. if h.ListenPort == 443 {
  562. h.ListenPort = 51821
  563. } else {
  564. h.ListenPort++
  565. }
  566. if h.ListenPort > maxPort {
  567. h.ListenPort = minPort
  568. }
  569. }
  570. return
  571. }
  572. // HostExists - checks if given host already exists
  573. func HostExists(h *models.Host) bool {
  574. _, err := GetHost(h.ID.String())
  575. return (err != nil && !database.IsEmptyRecord(err)) || (err == nil)
  576. }
  577. // GetHostByNodeID - returns a host if found to have a node's ID, else nil
  578. func GetHostByNodeID(id string) *models.Host {
  579. hosts, err := GetAllHosts()
  580. if err != nil {
  581. return nil
  582. }
  583. for i := range hosts {
  584. h := hosts[i]
  585. if StringSliceContains(h.Nodes, id) {
  586. return &h
  587. }
  588. }
  589. return nil
  590. }
  591. // ConvHostPassToHash - converts password to md5 hash
  592. func ConvHostPassToHash(hostPass string) string {
  593. return fmt.Sprintf("%x", md5.Sum([]byte(hostPass)))
  594. }
  595. // SortApiHosts - Sorts slice of ApiHosts by their ID alphabetically with numbers first
  596. func SortApiHosts(unsortedHosts []models.ApiHost) {
  597. sort.Slice(unsortedHosts, func(i, j int) bool {
  598. return unsortedHosts[i].ID < unsortedHosts[j].ID
  599. })
  600. }