hosts.go 16 KB

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