hosts.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. package logic
  2. import (
  3. "crypto/md5"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "os"
  8. "reflect"
  9. "sort"
  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. )
  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.String() != newHost.EndpointIP.String() {
  278. currHost.EndpointIP = newHost.EndpointIP
  279. sendPeerUpdate = true
  280. isEndpointChanged = true
  281. }
  282. if currHost.EndpointIPv6.String() != newHost.EndpointIPv6.String() {
  283. currHost.EndpointIPv6 = newHost.EndpointIPv6
  284. sendPeerUpdate = true
  285. isEndpointChanged = true
  286. }
  287. if !reflect.DeepEqual(currHost.Interfaces, newHost.Interfaces) {
  288. currHost.Interfaces = newHost.Interfaces
  289. sendPeerUpdate = true
  290. }
  291. if isEndpointChanged {
  292. for _, nodeID := range currHost.Nodes {
  293. node, err := GetNodeByID(nodeID)
  294. if err != nil {
  295. slog.Error("failed to get node:", "id", node.ID, "error", err)
  296. continue
  297. }
  298. if node.FailedOverBy != uuid.Nil {
  299. ResetFailedOverPeer(&node)
  300. }
  301. }
  302. }
  303. currHost.DaemonInstalled = newHost.DaemonInstalled
  304. currHost.Debug = newHost.Debug
  305. currHost.Verbosity = newHost.Verbosity
  306. currHost.Version = newHost.Version
  307. currHost.IsStaticPort = newHost.IsStaticPort
  308. currHost.IsStatic = newHost.IsStatic
  309. currHost.MTU = newHost.MTU
  310. currHost.Name = newHost.Name
  311. if len(newHost.NatType) > 0 && newHost.NatType != currHost.NatType {
  312. currHost.NatType = newHost.NatType
  313. sendPeerUpdate = true
  314. }
  315. return
  316. }
  317. // UpsertHost - upserts into DB a given host model, does not check for existence*
  318. func UpsertHost(h *models.Host) error {
  319. data, err := json.Marshal(h)
  320. if err != nil {
  321. return err
  322. }
  323. err = database.Insert(h.ID.String(), string(data), database.HOSTS_TABLE_NAME)
  324. if err != nil {
  325. return err
  326. }
  327. if servercfg.CacheEnabled() {
  328. storeHostInCache(*h)
  329. }
  330. return nil
  331. }
  332. // RemoveHost - removes a given host from server
  333. func RemoveHost(h *models.Host, forceDelete bool) error {
  334. if !forceDelete && len(h.Nodes) > 0 {
  335. return fmt.Errorf("host still has associated nodes")
  336. }
  337. if len(h.Nodes) > 0 {
  338. if err := DisassociateAllNodesFromHost(h.ID.String()); err != nil {
  339. return err
  340. }
  341. }
  342. err := database.DeleteRecord(database.HOSTS_TABLE_NAME, h.ID.String())
  343. if err != nil {
  344. return err
  345. }
  346. if servercfg.CacheEnabled() {
  347. deleteHostFromCache(h.ID.String())
  348. }
  349. go func() {
  350. if servercfg.IsDNSMode() {
  351. SetDNS()
  352. }
  353. }()
  354. return nil
  355. }
  356. // RemoveHostByID - removes a given host by id from server
  357. func RemoveHostByID(hostID string) error {
  358. err := database.DeleteRecord(database.HOSTS_TABLE_NAME, hostID)
  359. if err != nil {
  360. return err
  361. }
  362. if servercfg.CacheEnabled() {
  363. deleteHostFromCache(hostID)
  364. }
  365. return nil
  366. }
  367. // UpdateHostNetwork - adds/deletes host from a network
  368. func UpdateHostNetwork(h *models.Host, network string, add bool) (*models.Node, error) {
  369. for _, nodeID := range h.Nodes {
  370. node, err := GetNodeByID(nodeID)
  371. if err != nil || node.PendingDelete {
  372. continue
  373. }
  374. if node.Network == network {
  375. if !add {
  376. return &node, nil
  377. } else {
  378. return &node, errors.New("host already part of network " + network)
  379. }
  380. }
  381. }
  382. if !add {
  383. return nil, errors.New("host not part of the network " + network)
  384. } else {
  385. newNode := models.Node{}
  386. newNode.Server = servercfg.GetServer()
  387. newNode.Network = network
  388. newNode.HostID = h.ID
  389. if err := AssociateNodeToHost(&newNode, h); err != nil {
  390. return nil, err
  391. }
  392. return &newNode, nil
  393. }
  394. }
  395. // AssociateNodeToHost - associates and creates a node with a given host
  396. // should be the only way nodes get created as of 0.18
  397. func AssociateNodeToHost(n *models.Node, h *models.Host) error {
  398. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  399. return ErrInvalidHostID
  400. }
  401. n.HostID = h.ID
  402. err := createNode(n)
  403. if err != nil {
  404. return err
  405. }
  406. currentHost, err := GetHost(h.ID.String())
  407. if err != nil {
  408. return err
  409. }
  410. h.HostPass = currentHost.HostPass
  411. h.Nodes = append(currentHost.Nodes, n.ID.String())
  412. return UpsertHost(h)
  413. }
  414. // DissasociateNodeFromHost - deletes a node and removes from host nodes
  415. // should be the only way nodes are deleted as of 0.18
  416. func DissasociateNodeFromHost(n *models.Node, h *models.Host) error {
  417. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  418. return ErrInvalidHostID
  419. }
  420. if n.HostID != h.ID { // check if node actually belongs to host
  421. return fmt.Errorf("node is not associated with host")
  422. }
  423. if len(h.Nodes) == 0 {
  424. return fmt.Errorf("no nodes present in given host")
  425. }
  426. nList := []string{}
  427. for i := range h.Nodes {
  428. if h.Nodes[i] != n.ID.String() {
  429. nList = append(nList, h.Nodes[i])
  430. }
  431. }
  432. h.Nodes = nList
  433. go func() {
  434. if servercfg.IsPro {
  435. if clients, err := GetNetworkExtClients(n.Network); err != nil {
  436. for i := range clients {
  437. AllowClientNodeAccess(&clients[i], n.ID.String())
  438. }
  439. }
  440. }
  441. }()
  442. if err := DeleteNodeByID(n); err != nil {
  443. return err
  444. }
  445. return UpsertHost(h)
  446. }
  447. // DisassociateAllNodesFromHost - deletes all nodes of the host
  448. func DisassociateAllNodesFromHost(hostID string) error {
  449. host, err := GetHost(hostID)
  450. if err != nil {
  451. return err
  452. }
  453. for _, nodeID := range host.Nodes {
  454. node, err := GetNodeByID(nodeID)
  455. if err != nil {
  456. logger.Log(0, "failed to get host node, node id:", nodeID, err.Error())
  457. continue
  458. }
  459. if err := DeleteNode(&node, true); err != nil {
  460. logger.Log(0, "failed to delete node", node.ID.String(), err.Error())
  461. continue
  462. }
  463. logger.Log(3, "deleted node", node.ID.String(), "of host", host.ID.String())
  464. }
  465. host.Nodes = []string{}
  466. return UpsertHost(host)
  467. }
  468. // GetDefaultHosts - retrieve all hosts marked as default from DB
  469. func GetDefaultHosts() []models.Host {
  470. defaultHostList := []models.Host{}
  471. hosts, err := GetAllHosts()
  472. if err != nil {
  473. return defaultHostList
  474. }
  475. for i := range hosts {
  476. if hosts[i].IsDefault {
  477. defaultHostList = append(defaultHostList, hosts[i])
  478. }
  479. }
  480. return defaultHostList[:]
  481. }
  482. // GetHostNetworks - fetches all the networks
  483. func GetHostNetworks(hostID string) []string {
  484. currHost, err := GetHost(hostID)
  485. if err != nil {
  486. return nil
  487. }
  488. nets := []string{}
  489. for i := range currHost.Nodes {
  490. n, err := GetNodeByID(currHost.Nodes[i])
  491. if err != nil {
  492. return nil
  493. }
  494. nets = append(nets, n.Network)
  495. }
  496. return nets
  497. }
  498. // GetRelatedHosts - fetches related hosts of a given host
  499. func GetRelatedHosts(hostID string) []models.Host {
  500. relatedHosts := []models.Host{}
  501. networks := GetHostNetworks(hostID)
  502. networkMap := make(map[string]struct{})
  503. for _, network := range networks {
  504. networkMap[network] = struct{}{}
  505. }
  506. hosts, err := GetAllHosts()
  507. if err == nil {
  508. for _, host := range hosts {
  509. if host.ID.String() == hostID {
  510. continue
  511. }
  512. networks := GetHostNetworks(host.ID.String())
  513. for _, network := range networks {
  514. if _, ok := networkMap[network]; ok {
  515. relatedHosts = append(relatedHosts, host)
  516. break
  517. }
  518. }
  519. }
  520. }
  521. return relatedHosts
  522. }
  523. // CheckHostPort checks host endpoints to ensures that hosts on the same server
  524. // with the same endpoint have different listen ports
  525. // in the case of 64535 hosts or more with same endpoint, ports will not be changed
  526. func CheckHostPorts(h *models.Host) (changed bool) {
  527. portsInUse := make(map[int]bool, 0)
  528. hosts, err := GetAllHosts()
  529. if err != nil {
  530. return
  531. }
  532. originalPort := h.ListenPort
  533. defer func() {
  534. if originalPort != h.ListenPort {
  535. changed = true
  536. }
  537. }()
  538. if h.EndpointIP == nil {
  539. return
  540. }
  541. for _, host := range hosts {
  542. if host.ID.String() == h.ID.String() {
  543. // skip self
  544. continue
  545. }
  546. if host.EndpointIP == nil {
  547. continue
  548. }
  549. if !host.EndpointIP.Equal(h.EndpointIP) {
  550. continue
  551. }
  552. portsInUse[host.ListenPort] = true
  553. }
  554. // iterate until port is not found or max iteration is reached
  555. for i := 0; portsInUse[h.ListenPort] && i < maxPort-minPort+1; i++ {
  556. if h.ListenPort == 443 {
  557. h.ListenPort = 51821
  558. } else {
  559. h.ListenPort++
  560. }
  561. if h.ListenPort > maxPort {
  562. h.ListenPort = minPort
  563. }
  564. }
  565. return
  566. }
  567. // HostExists - checks if given host already exists
  568. func HostExists(h *models.Host) bool {
  569. _, err := GetHost(h.ID.String())
  570. return (err != nil && !database.IsEmptyRecord(err)) || (err == nil)
  571. }
  572. // GetHostByNodeID - returns a host if found to have a node's ID, else nil
  573. func GetHostByNodeID(id string) *models.Host {
  574. hosts, err := GetAllHosts()
  575. if err != nil {
  576. return nil
  577. }
  578. for i := range hosts {
  579. h := hosts[i]
  580. if StringSliceContains(h.Nodes, id) {
  581. return &h
  582. }
  583. }
  584. return nil
  585. }
  586. // ConvHostPassToHash - converts password to md5 hash
  587. func ConvHostPassToHash(hostPass string) string {
  588. return fmt.Sprintf("%x", md5.Sum([]byte(hostPass)))
  589. }
  590. // SortApiHosts - Sorts slice of ApiHosts by their ID alphabetically with numbers first
  591. func SortApiHosts(unsortedHosts []models.ApiHost) {
  592. sort.Slice(unsortedHosts, func(i, j int) bool {
  593. return unsortedHosts[i].ID < unsortedHosts[j].ID
  594. })
  595. }