hosts.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  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. // GetHost - gets a host from db given id
  156. func GetHost(hostid string) (*models.Host, error) {
  157. if servercfg.CacheEnabled() {
  158. if host, ok := getHostFromCache(hostid); ok {
  159. return &host, nil
  160. }
  161. }
  162. record, err := database.FetchRecord(database.HOSTS_TABLE_NAME, hostid)
  163. if err != nil {
  164. return nil, err
  165. }
  166. var h models.Host
  167. if err = json.Unmarshal([]byte(record), &h); err != nil {
  168. return nil, err
  169. }
  170. if servercfg.CacheEnabled() {
  171. storeHostInCache(h)
  172. }
  173. return &h, nil
  174. }
  175. // GetHostByPubKey - gets a host from db given pubkey
  176. func GetHostByPubKey(hostPubKey string) (*models.Host, error) {
  177. hosts, err := GetAllHosts()
  178. if err != nil {
  179. return nil, err
  180. }
  181. for _, host := range hosts {
  182. if host.PublicKey.String() == hostPubKey {
  183. return &host, nil
  184. }
  185. }
  186. return nil, errors.New("host not found")
  187. }
  188. // CreateHost - creates a host if not exist
  189. func CreateHost(h *models.Host) error {
  190. hosts, hErr := GetAllHosts()
  191. clients, cErr := GetAllExtClients()
  192. if (hErr != nil && !database.IsEmptyRecord(hErr)) ||
  193. (cErr != nil && !database.IsEmptyRecord(cErr)) ||
  194. len(hosts)+len(clients) >= MachinesLimit {
  195. return errors.New("free tier limits exceeded on machines")
  196. }
  197. _, err := GetHost(h.ID.String())
  198. if (err != nil && !database.IsEmptyRecord(err)) || (err == nil) {
  199. return ErrHostExists
  200. }
  201. // encrypt that password so we never see it
  202. hash, err := bcrypt.GenerateFromPassword([]byte(h.HostPass), 5)
  203. if err != nil {
  204. return err
  205. }
  206. h.HostPass = string(hash)
  207. h.AutoUpdate = AutoUpdateEnabled()
  208. if GetServerSettings().ManageDNS {
  209. h.DNS = "yes"
  210. } else {
  211. h.DNS = "no"
  212. }
  213. if h.EndpointIP != nil {
  214. h.Location = GetHostLocInfo(h.EndpointIP.String(), os.Getenv("IP_INFO_TOKEN"))
  215. } else if h.EndpointIPv6 != nil {
  216. h.Location = GetHostLocInfo(h.EndpointIPv6.String(), os.Getenv("IP_INFO_TOKEN"))
  217. }
  218. checkForZombieHosts(h)
  219. return UpsertHost(h)
  220. }
  221. // UpdateHost - updates host data by field
  222. func UpdateHost(newHost, currentHost *models.Host) {
  223. // unchangeable fields via API here
  224. newHost.DaemonInstalled = currentHost.DaemonInstalled
  225. newHost.OS = currentHost.OS
  226. newHost.IPForwarding = currentHost.IPForwarding
  227. newHost.HostPass = currentHost.HostPass
  228. newHost.MacAddress = currentHost.MacAddress
  229. newHost.Debug = currentHost.Debug
  230. newHost.Nodes = currentHost.Nodes
  231. newHost.PublicKey = currentHost.PublicKey
  232. newHost.TrafficKeyPublic = currentHost.TrafficKeyPublic
  233. // changeable fields
  234. if len(newHost.Version) == 0 {
  235. newHost.Version = currentHost.Version
  236. }
  237. if len(newHost.Name) == 0 {
  238. newHost.Name = currentHost.Name
  239. }
  240. if newHost.MTU == 0 {
  241. newHost.MTU = currentHost.MTU
  242. }
  243. if newHost.ListenPort == 0 {
  244. newHost.ListenPort = currentHost.ListenPort
  245. }
  246. if newHost.PersistentKeepalive == 0 {
  247. newHost.PersistentKeepalive = currentHost.PersistentKeepalive
  248. }
  249. }
  250. // UpdateHostFromClient - used for updating host on server with update recieved from client
  251. func UpdateHostFromClient(newHost, currHost *models.Host) (sendPeerUpdate bool) {
  252. if newHost.PublicKey != currHost.PublicKey {
  253. currHost.PublicKey = newHost.PublicKey
  254. sendPeerUpdate = true
  255. }
  256. if newHost.ListenPort != 0 && currHost.ListenPort != newHost.ListenPort {
  257. currHost.ListenPort = newHost.ListenPort
  258. sendPeerUpdate = true
  259. }
  260. if newHost.WgPublicListenPort != 0 &&
  261. currHost.WgPublicListenPort != newHost.WgPublicListenPort {
  262. currHost.WgPublicListenPort = newHost.WgPublicListenPort
  263. sendPeerUpdate = true
  264. }
  265. isEndpointChanged := false
  266. if currHost.EndpointIP.String() != newHost.EndpointIP.String() {
  267. currHost.EndpointIP = newHost.EndpointIP
  268. sendPeerUpdate = true
  269. isEndpointChanged = true
  270. }
  271. if currHost.EndpointIPv6.String() != newHost.EndpointIPv6.String() {
  272. currHost.EndpointIPv6 = newHost.EndpointIPv6
  273. sendPeerUpdate = true
  274. isEndpointChanged = true
  275. }
  276. if !reflect.DeepEqual(currHost.Interfaces, newHost.Interfaces) {
  277. currHost.Interfaces = newHost.Interfaces
  278. sendPeerUpdate = true
  279. }
  280. if isEndpointChanged {
  281. for _, nodeID := range currHost.Nodes {
  282. node, err := GetNodeByID(nodeID)
  283. if err != nil {
  284. slog.Error("failed to get node:", "id", node.ID, "error", err)
  285. continue
  286. }
  287. if node.FailedOverBy != uuid.Nil {
  288. ResetFailedOverPeer(&node)
  289. }
  290. }
  291. }
  292. currHost.DaemonInstalled = newHost.DaemonInstalled
  293. currHost.Debug = newHost.Debug
  294. currHost.Verbosity = newHost.Verbosity
  295. currHost.Version = newHost.Version
  296. currHost.IsStaticPort = newHost.IsStaticPort
  297. currHost.IsStatic = newHost.IsStatic
  298. currHost.MTU = newHost.MTU
  299. currHost.Name = newHost.Name
  300. if len(newHost.NatType) > 0 && newHost.NatType != currHost.NatType {
  301. currHost.NatType = newHost.NatType
  302. sendPeerUpdate = true
  303. }
  304. return
  305. }
  306. // UpsertHost - upserts into DB a given host model, does not check for existence*
  307. func UpsertHost(h *models.Host) error {
  308. data, err := json.Marshal(h)
  309. if err != nil {
  310. return err
  311. }
  312. err = database.Insert(h.ID.String(), string(data), database.HOSTS_TABLE_NAME)
  313. if err != nil {
  314. return err
  315. }
  316. if servercfg.CacheEnabled() {
  317. storeHostInCache(*h)
  318. }
  319. return nil
  320. }
  321. // RemoveHost - removes a given host from server
  322. func RemoveHost(h *models.Host, forceDelete bool) error {
  323. if !forceDelete && len(h.Nodes) > 0 {
  324. return fmt.Errorf("host still has associated nodes")
  325. }
  326. if len(h.Nodes) > 0 {
  327. if err := DisassociateAllNodesFromHost(h.ID.String()); err != nil {
  328. return err
  329. }
  330. }
  331. err := database.DeleteRecord(database.HOSTS_TABLE_NAME, h.ID.String())
  332. if err != nil {
  333. return err
  334. }
  335. if servercfg.CacheEnabled() {
  336. deleteHostFromCache(h.ID.String())
  337. }
  338. go func() {
  339. if servercfg.IsDNSMode() {
  340. SetDNS()
  341. }
  342. }()
  343. return nil
  344. }
  345. // RemoveHostByID - removes a given host by id from server
  346. func RemoveHostByID(hostID string) error {
  347. err := database.DeleteRecord(database.HOSTS_TABLE_NAME, hostID)
  348. if err != nil {
  349. return err
  350. }
  351. if servercfg.CacheEnabled() {
  352. deleteHostFromCache(hostID)
  353. }
  354. return nil
  355. }
  356. // UpdateHostNetwork - adds/deletes host from a network
  357. func UpdateHostNetwork(h *models.Host, network string, add bool) (*models.Node, error) {
  358. for _, nodeID := range h.Nodes {
  359. node, err := GetNodeByID(nodeID)
  360. if err != nil || node.PendingDelete {
  361. continue
  362. }
  363. if node.Network == network {
  364. if !add {
  365. return &node, nil
  366. } else {
  367. return &node, errors.New("host already part of network " + network)
  368. }
  369. }
  370. }
  371. if !add {
  372. return nil, errors.New("host not part of the network " + network)
  373. } else {
  374. newNode := models.Node{}
  375. newNode.Server = servercfg.GetServer()
  376. newNode.Network = network
  377. newNode.HostID = h.ID
  378. if err := AssociateNodeToHost(&newNode, h); err != nil {
  379. return nil, err
  380. }
  381. return &newNode, nil
  382. }
  383. }
  384. // AssociateNodeToHost - associates and creates a node with a given host
  385. // should be the only way nodes get created as of 0.18
  386. func AssociateNodeToHost(n *models.Node, h *models.Host) error {
  387. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  388. return ErrInvalidHostID
  389. }
  390. n.HostID = h.ID
  391. err := createNode(n)
  392. if err != nil {
  393. return err
  394. }
  395. currentHost, err := GetHost(h.ID.String())
  396. if err != nil {
  397. return err
  398. }
  399. h.HostPass = currentHost.HostPass
  400. h.Nodes = append(currentHost.Nodes, n.ID.String())
  401. return UpsertHost(h)
  402. }
  403. // DissasociateNodeFromHost - deletes a node and removes from host nodes
  404. // should be the only way nodes are deleted as of 0.18
  405. func DissasociateNodeFromHost(n *models.Node, h *models.Host) error {
  406. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  407. return ErrInvalidHostID
  408. }
  409. if n.HostID != h.ID { // check if node actually belongs to host
  410. return fmt.Errorf("node is not associated with host")
  411. }
  412. if len(h.Nodes) == 0 {
  413. return fmt.Errorf("no nodes present in given host")
  414. }
  415. nList := []string{}
  416. for i := range h.Nodes {
  417. if h.Nodes[i] != n.ID.String() {
  418. nList = append(nList, h.Nodes[i])
  419. }
  420. }
  421. h.Nodes = nList
  422. go func() {
  423. if servercfg.IsPro {
  424. if clients, err := GetNetworkExtClients(n.Network); err != nil {
  425. for i := range clients {
  426. AllowClientNodeAccess(&clients[i], n.ID.String())
  427. }
  428. }
  429. }
  430. }()
  431. if err := DeleteNodeByID(n); err != nil {
  432. return err
  433. }
  434. return UpsertHost(h)
  435. }
  436. // DisassociateAllNodesFromHost - deletes all nodes of the host
  437. func DisassociateAllNodesFromHost(hostID string) error {
  438. host, err := GetHost(hostID)
  439. if err != nil {
  440. return err
  441. }
  442. for _, nodeID := range host.Nodes {
  443. node, err := GetNodeByID(nodeID)
  444. if err != nil {
  445. logger.Log(0, "failed to get host node, node id:", nodeID, err.Error())
  446. continue
  447. }
  448. if err := DeleteNode(&node, true); err != nil {
  449. logger.Log(0, "failed to delete node", node.ID.String(), err.Error())
  450. continue
  451. }
  452. logger.Log(3, "deleted node", node.ID.String(), "of host", host.ID.String())
  453. }
  454. host.Nodes = []string{}
  455. return UpsertHost(host)
  456. }
  457. // GetDefaultHosts - retrieve all hosts marked as default from DB
  458. func GetDefaultHosts() []models.Host {
  459. defaultHostList := []models.Host{}
  460. hosts, err := GetAllHosts()
  461. if err != nil {
  462. return defaultHostList
  463. }
  464. for i := range hosts {
  465. if hosts[i].IsDefault {
  466. defaultHostList = append(defaultHostList, hosts[i])
  467. }
  468. }
  469. return defaultHostList[:]
  470. }
  471. // GetHostNetworks - fetches all the networks
  472. func GetHostNetworks(hostID string) []string {
  473. currHost, err := GetHost(hostID)
  474. if err != nil {
  475. return nil
  476. }
  477. nets := []string{}
  478. for i := range currHost.Nodes {
  479. n, err := GetNodeByID(currHost.Nodes[i])
  480. if err != nil {
  481. return nil
  482. }
  483. nets = append(nets, n.Network)
  484. }
  485. return nets
  486. }
  487. // GetRelatedHosts - fetches related hosts of a given host
  488. func GetRelatedHosts(hostID string) []models.Host {
  489. relatedHosts := []models.Host{}
  490. networks := GetHostNetworks(hostID)
  491. networkMap := make(map[string]struct{})
  492. for _, network := range networks {
  493. networkMap[network] = struct{}{}
  494. }
  495. hosts, err := GetAllHosts()
  496. if err == nil {
  497. for _, host := range hosts {
  498. if host.ID.String() == hostID {
  499. continue
  500. }
  501. networks := GetHostNetworks(host.ID.String())
  502. for _, network := range networks {
  503. if _, ok := networkMap[network]; ok {
  504. relatedHosts = append(relatedHosts, host)
  505. break
  506. }
  507. }
  508. }
  509. }
  510. return relatedHosts
  511. }
  512. // CheckHostPort checks host endpoints to ensures that hosts on the same server
  513. // with the same endpoint have different listen ports
  514. // in the case of 64535 hosts or more with same endpoint, ports will not be changed
  515. func CheckHostPorts(h *models.Host) (changed bool) {
  516. portsInUse := make(map[int]bool, 0)
  517. hosts, err := GetAllHosts()
  518. if err != nil {
  519. return
  520. }
  521. originalPort := h.ListenPort
  522. defer func() {
  523. if originalPort != h.ListenPort {
  524. changed = true
  525. }
  526. }()
  527. if h.EndpointIP == nil {
  528. return
  529. }
  530. for _, host := range hosts {
  531. if host.ID.String() == h.ID.String() {
  532. // skip self
  533. continue
  534. }
  535. if host.EndpointIP == nil {
  536. continue
  537. }
  538. if !host.EndpointIP.Equal(h.EndpointIP) {
  539. continue
  540. }
  541. portsInUse[host.ListenPort] = true
  542. }
  543. // iterate until port is not found or max iteration is reached
  544. for i := 0; portsInUse[h.ListenPort] && i < maxPort-minPort+1; i++ {
  545. if h.ListenPort == 443 {
  546. h.ListenPort = 51821
  547. } else {
  548. h.ListenPort++
  549. }
  550. if h.ListenPort > maxPort {
  551. h.ListenPort = minPort
  552. }
  553. }
  554. return
  555. }
  556. // HostExists - checks if given host already exists
  557. func HostExists(h *models.Host) bool {
  558. _, err := GetHost(h.ID.String())
  559. return (err != nil && !database.IsEmptyRecord(err)) || (err == nil)
  560. }
  561. // GetHostByNodeID - returns a host if found to have a node's ID, else nil
  562. func GetHostByNodeID(id string) *models.Host {
  563. hosts, err := GetAllHosts()
  564. if err != nil {
  565. return nil
  566. }
  567. for i := range hosts {
  568. h := hosts[i]
  569. if StringSliceContains(h.Nodes, id) {
  570. return &h
  571. }
  572. }
  573. return nil
  574. }
  575. // ConvHostPassToHash - converts password to md5 hash
  576. func ConvHostPassToHash(hostPass string) string {
  577. return fmt.Sprintf("%x", md5.Sum([]byte(hostPass)))
  578. }
  579. // SortApiHosts - Sorts slice of ApiHosts by their ID alphabetically with numbers first
  580. func SortApiHosts(unsortedHosts []models.ApiHost) {
  581. sort.Slice(unsortedHosts, func(i, j int) bool {
  582. return unsortedHosts[i].ID < unsortedHosts[j].ID
  583. })
  584. }