hosts.go 15 KB

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