hosts.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. package logic
  2. import (
  3. "crypto/md5"
  4. "encoding/base64"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "net/http"
  9. "sort"
  10. "strconv"
  11. "sync"
  12. "github.com/devilcove/httpclient"
  13. "github.com/google/uuid"
  14. "golang.org/x/crypto/bcrypt"
  15. "github.com/gravitl/netmaker/database"
  16. "github.com/gravitl/netmaker/logger"
  17. "github.com/gravitl/netmaker/models"
  18. "github.com/gravitl/netmaker/servercfg"
  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. 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. // GetAllHostsAPI - get's all the hosts in an API usable format
  98. func GetAllHostsAPI(hosts []models.Host) []models.ApiHost {
  99. apiHosts := []models.ApiHost{}
  100. for i := range hosts {
  101. newApiHost := hosts[i].ConvertNMHostToAPI()
  102. apiHosts = append(apiHosts, *newApiHost)
  103. }
  104. return apiHosts[:]
  105. }
  106. // GetHostsMap - gets all the current hosts on machine in a map
  107. func GetHostsMap() (map[string]models.Host, error) {
  108. if servercfg.CacheEnabled() {
  109. hostsMap := getHostsMapFromCache()
  110. if len(hostsMap) != 0 {
  111. return hostsMap, nil
  112. }
  113. }
  114. records, err := database.FetchRecords(database.HOSTS_TABLE_NAME)
  115. if err != nil && !database.IsEmptyRecord(err) {
  116. return nil, err
  117. }
  118. currHostMap := make(map[string]models.Host)
  119. if servercfg.CacheEnabled() {
  120. defer loadHostsIntoCache(currHostMap)
  121. }
  122. for k := range records {
  123. var h models.Host
  124. err = json.Unmarshal([]byte(records[k]), &h)
  125. if err != nil {
  126. return nil, err
  127. }
  128. currHostMap[h.ID.String()] = h
  129. }
  130. return currHostMap, nil
  131. }
  132. // GetHost - gets a host from db given id
  133. func GetHost(hostid string) (*models.Host, error) {
  134. if servercfg.CacheEnabled() {
  135. if host, ok := getHostFromCache(hostid); ok {
  136. return &host, nil
  137. }
  138. }
  139. record, err := database.FetchRecord(database.HOSTS_TABLE_NAME, hostid)
  140. if err != nil {
  141. return nil, err
  142. }
  143. var h models.Host
  144. if err = json.Unmarshal([]byte(record), &h); err != nil {
  145. return nil, err
  146. }
  147. if servercfg.CacheEnabled() {
  148. storeHostInCache(h)
  149. }
  150. return &h, nil
  151. }
  152. // GetHostByPubKey - gets a host from db given pubkey
  153. func GetHostByPubKey(hostPubKey string) (*models.Host, error) {
  154. hosts, err := GetAllHosts()
  155. if err != nil {
  156. return nil, err
  157. }
  158. for _, host := range hosts {
  159. if host.PublicKey.String() == hostPubKey {
  160. return &host, nil
  161. }
  162. }
  163. return nil, errors.New("host not found")
  164. }
  165. // CreateHost - creates a host if not exist
  166. func CreateHost(h *models.Host) error {
  167. hosts, hErr := GetAllHosts()
  168. clients, cErr := GetAllExtClients()
  169. if (hErr != nil && !database.IsEmptyRecord(hErr)) ||
  170. (cErr != nil && !database.IsEmptyRecord(cErr)) ||
  171. len(hosts)+len(clients) >= MachinesLimit {
  172. return errors.New("free tier limits exceeded on machines")
  173. }
  174. _, err := GetHost(h.ID.String())
  175. if (err != nil && !database.IsEmptyRecord(err)) || (err == nil) {
  176. return ErrHostExists
  177. }
  178. if servercfg.IsUsingTurn() {
  179. err = RegisterHostWithTurn(h.ID.String(), h.HostPass)
  180. if err != nil {
  181. logger.Log(0, "failed to register host with turn server: ", err.Error())
  182. }
  183. }
  184. // encrypt that password so we never see it
  185. hash, err := bcrypt.GenerateFromPassword([]byte(h.HostPass), 5)
  186. if err != nil {
  187. return err
  188. }
  189. h.HostPass = string(hash)
  190. h.AutoUpdate = servercfg.AutoUpdateEnabled()
  191. checkForZombieHosts(h)
  192. return UpsertHost(h)
  193. }
  194. // UpdateHost - updates host data by field
  195. func UpdateHost(newHost, currentHost *models.Host) {
  196. // unchangeable fields via API here
  197. newHost.DaemonInstalled = currentHost.DaemonInstalled
  198. newHost.OS = currentHost.OS
  199. newHost.IPForwarding = currentHost.IPForwarding
  200. newHost.HostPass = currentHost.HostPass
  201. newHost.MacAddress = currentHost.MacAddress
  202. newHost.Debug = currentHost.Debug
  203. newHost.Nodes = currentHost.Nodes
  204. newHost.PublicKey = currentHost.PublicKey
  205. newHost.TrafficKeyPublic = currentHost.TrafficKeyPublic
  206. // changeable fields
  207. if len(newHost.Version) == 0 {
  208. newHost.Version = currentHost.Version
  209. }
  210. if len(newHost.Name) == 0 {
  211. newHost.Name = currentHost.Name
  212. }
  213. if newHost.MTU == 0 {
  214. newHost.MTU = currentHost.MTU
  215. }
  216. if newHost.ListenPort == 0 {
  217. newHost.ListenPort = currentHost.ListenPort
  218. }
  219. if newHost.PersistentKeepalive == 0 {
  220. newHost.PersistentKeepalive = currentHost.PersistentKeepalive
  221. }
  222. }
  223. // UpdateHostFromClient - used for updating host on server with update recieved from client
  224. func UpdateHostFromClient(newHost, currHost *models.Host) (sendPeerUpdate bool) {
  225. if newHost.PublicKey != currHost.PublicKey {
  226. currHost.PublicKey = newHost.PublicKey
  227. sendPeerUpdate = true
  228. }
  229. if newHost.ListenPort != 0 && currHost.ListenPort != newHost.ListenPort {
  230. currHost.ListenPort = newHost.ListenPort
  231. sendPeerUpdate = true
  232. }
  233. if newHost.WgPublicListenPort != 0 &&
  234. currHost.WgPublicListenPort != newHost.WgPublicListenPort {
  235. currHost.WgPublicListenPort = newHost.WgPublicListenPort
  236. sendPeerUpdate = true
  237. }
  238. if currHost.EndpointIP.String() != newHost.EndpointIP.String() {
  239. currHost.EndpointIP = newHost.EndpointIP
  240. sendPeerUpdate = true
  241. }
  242. currHost.DaemonInstalled = newHost.DaemonInstalled
  243. currHost.Debug = newHost.Debug
  244. currHost.Verbosity = newHost.Verbosity
  245. currHost.Version = newHost.Version
  246. currHost.IsStatic = newHost.IsStatic
  247. currHost.MTU = newHost.MTU
  248. currHost.Name = newHost.Name
  249. if len(newHost.NatType) > 0 && newHost.NatType != currHost.NatType {
  250. currHost.NatType = newHost.NatType
  251. sendPeerUpdate = true
  252. }
  253. return
  254. }
  255. // UpsertHost - upserts into DB a given host model, does not check for existence*
  256. func UpsertHost(h *models.Host) error {
  257. data, err := json.Marshal(h)
  258. if err != nil {
  259. return err
  260. }
  261. err = database.Insert(h.ID.String(), string(data), database.HOSTS_TABLE_NAME)
  262. if err != nil {
  263. return err
  264. }
  265. if servercfg.CacheEnabled() {
  266. storeHostInCache(*h)
  267. }
  268. return nil
  269. }
  270. // RemoveHost - removes a given host from server
  271. func RemoveHost(h *models.Host, forceDelete bool) error {
  272. if !forceDelete && len(h.Nodes) > 0 {
  273. return fmt.Errorf("host still has associated nodes")
  274. }
  275. if servercfg.IsUsingTurn() {
  276. DeRegisterHostWithTurn(h.ID.String())
  277. }
  278. if len(h.Nodes) > 0 {
  279. if err := DisassociateAllNodesFromHost(h.ID.String()); err != nil {
  280. return err
  281. }
  282. }
  283. err := database.DeleteRecord(database.HOSTS_TABLE_NAME, h.ID.String())
  284. if err != nil {
  285. return err
  286. }
  287. if servercfg.CacheEnabled() {
  288. deleteHostFromCache(h.ID.String())
  289. }
  290. return nil
  291. }
  292. // RemoveHostByID - removes a given host by id from server
  293. func RemoveHostByID(hostID string) error {
  294. if servercfg.IsUsingTurn() {
  295. DeRegisterHostWithTurn(hostID)
  296. }
  297. err := database.DeleteRecord(database.HOSTS_TABLE_NAME, hostID)
  298. if err != nil {
  299. return err
  300. }
  301. if servercfg.CacheEnabled() {
  302. deleteHostFromCache(hostID)
  303. }
  304. return nil
  305. }
  306. // UpdateHostNetwork - adds/deletes host from a network
  307. func UpdateHostNetwork(h *models.Host, network string, add bool) (*models.Node, error) {
  308. for _, nodeID := range h.Nodes {
  309. node, err := GetNodeByID(nodeID)
  310. if err != nil || node.PendingDelete {
  311. continue
  312. }
  313. if node.Network == network {
  314. if !add {
  315. return &node, nil
  316. } else {
  317. return nil, errors.New("host already part of network " + network)
  318. }
  319. }
  320. }
  321. if !add {
  322. return nil, errors.New("host not part of the network " + network)
  323. } else {
  324. newNode := models.Node{}
  325. newNode.Server = servercfg.GetServer()
  326. newNode.Network = network
  327. newNode.HostID = h.ID
  328. if err := AssociateNodeToHost(&newNode, h); err != nil {
  329. return nil, err
  330. }
  331. return &newNode, nil
  332. }
  333. }
  334. // AssociateNodeToHost - associates and creates a node with a given host
  335. // should be the only way nodes get created as of 0.18
  336. func AssociateNodeToHost(n *models.Node, h *models.Host) error {
  337. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  338. return ErrInvalidHostID
  339. }
  340. n.HostID = h.ID
  341. err := createNode(n)
  342. if err != nil {
  343. return err
  344. }
  345. currentHost, err := GetHost(h.ID.String())
  346. if err != nil {
  347. return err
  348. }
  349. h.HostPass = currentHost.HostPass
  350. h.Nodes = append(currentHost.Nodes, n.ID.String())
  351. return UpsertHost(h)
  352. }
  353. // DissasociateNodeFromHost - deletes a node and removes from host nodes
  354. // should be the only way nodes are deleted as of 0.18
  355. func DissasociateNodeFromHost(n *models.Node, h *models.Host) error {
  356. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  357. return ErrInvalidHostID
  358. }
  359. if n.HostID != h.ID { // check if node actually belongs to host
  360. return fmt.Errorf("node is not associated with host")
  361. }
  362. if len(h.Nodes) == 0 {
  363. return fmt.Errorf("no nodes present in given host")
  364. }
  365. index := -1
  366. for i := range h.Nodes {
  367. if h.Nodes[i] == n.ID.String() {
  368. index = i
  369. break
  370. }
  371. }
  372. if index < 0 {
  373. if len(h.Nodes) == 0 {
  374. return fmt.Errorf("node %s, not found in host, %s", n.ID.String(), h.ID.String())
  375. }
  376. } else {
  377. h.Nodes = RemoveStringSlice(h.Nodes, index)
  378. }
  379. go func() {
  380. if servercfg.IsPro {
  381. if clients, err := GetNetworkExtClients(n.Network); err != nil {
  382. for i := range clients {
  383. AllowClientNodeAccess(&clients[i], n.ID.String())
  384. }
  385. }
  386. }
  387. }()
  388. if err := DeleteNodeByID(n); err != nil {
  389. return err
  390. }
  391. return UpsertHost(h)
  392. }
  393. // DisassociateAllNodesFromHost - deletes all nodes of the host
  394. func DisassociateAllNodesFromHost(hostID string) error {
  395. host, err := GetHost(hostID)
  396. if err != nil {
  397. return err
  398. }
  399. for _, nodeID := range host.Nodes {
  400. node, err := GetNodeByID(nodeID)
  401. if err != nil {
  402. logger.Log(0, "failed to get host node", err.Error())
  403. continue
  404. }
  405. if err := DeleteNode(&node, true); err != nil {
  406. logger.Log(0, "failed to delete node", node.ID.String(), err.Error())
  407. continue
  408. }
  409. logger.Log(3, "deleted node", node.ID.String(), "of host", host.ID.String())
  410. }
  411. host.Nodes = []string{}
  412. return UpsertHost(host)
  413. }
  414. // GetDefaultHosts - retrieve all hosts marked as default from DB
  415. func GetDefaultHosts() []models.Host {
  416. defaultHostList := []models.Host{}
  417. hosts, err := GetAllHosts()
  418. if err != nil {
  419. return defaultHostList
  420. }
  421. for i := range hosts {
  422. if hosts[i].IsDefault {
  423. defaultHostList = append(defaultHostList, hosts[i])
  424. }
  425. }
  426. return defaultHostList[:]
  427. }
  428. // GetHostNetworks - fetches all the networks
  429. func GetHostNetworks(hostID string) []string {
  430. currHost, err := GetHost(hostID)
  431. if err != nil {
  432. return nil
  433. }
  434. nets := []string{}
  435. for i := range currHost.Nodes {
  436. n, err := GetNodeByID(currHost.Nodes[i])
  437. if err != nil {
  438. return nil
  439. }
  440. nets = append(nets, n.Network)
  441. }
  442. return nets
  443. }
  444. // GetRelatedHosts - fetches related hosts of a given host
  445. func GetRelatedHosts(hostID string) []models.Host {
  446. relatedHosts := []models.Host{}
  447. networks := GetHostNetworks(hostID)
  448. networkMap := make(map[string]struct{})
  449. for _, network := range networks {
  450. networkMap[network] = struct{}{}
  451. }
  452. hosts, err := GetAllHosts()
  453. if err == nil {
  454. for _, host := range hosts {
  455. if host.ID.String() == hostID {
  456. continue
  457. }
  458. networks := GetHostNetworks(host.ID.String())
  459. for _, network := range networks {
  460. if _, ok := networkMap[network]; ok {
  461. relatedHosts = append(relatedHosts, host)
  462. break
  463. }
  464. }
  465. }
  466. }
  467. return relatedHosts
  468. }
  469. // CheckHostPort checks host endpoints to ensures that hosts on the same server
  470. // with the same endpoint have different listen ports
  471. // in the case of 64535 hosts or more with same endpoint, ports will not be changed
  472. func CheckHostPorts(h *models.Host) {
  473. portsInUse := make(map[int]bool, 0)
  474. hosts, err := GetAllHosts()
  475. if err != nil {
  476. return
  477. }
  478. for _, host := range hosts {
  479. if host.ID.String() == h.ID.String() {
  480. // skip self
  481. continue
  482. }
  483. if !host.EndpointIP.Equal(h.EndpointIP) {
  484. continue
  485. }
  486. portsInUse[host.ListenPort] = true
  487. }
  488. // iterate until port is not found or max iteration is reached
  489. for i := 0; portsInUse[h.ListenPort] && i < maxPort-minPort+1; i++ {
  490. h.ListenPort++
  491. if h.ListenPort > maxPort {
  492. h.ListenPort = minPort
  493. }
  494. }
  495. }
  496. // HostExists - checks if given host already exists
  497. func HostExists(h *models.Host) bool {
  498. _, err := GetHost(h.ID.String())
  499. return (err != nil && !database.IsEmptyRecord(err)) || (err == nil)
  500. }
  501. // GetHostByNodeID - returns a host if found to have a node's ID, else nil
  502. func GetHostByNodeID(id string) *models.Host {
  503. hosts, err := GetAllHosts()
  504. if err != nil {
  505. return nil
  506. }
  507. for i := range hosts {
  508. h := hosts[i]
  509. if StringSliceContains(h.Nodes, id) {
  510. return &h
  511. }
  512. }
  513. return nil
  514. }
  515. // ConvHostPassToHash - converts password to md5 hash
  516. func ConvHostPassToHash(hostPass string) string {
  517. return fmt.Sprintf("%x", md5.Sum([]byte(hostPass)))
  518. }
  519. // RegisterHostWithTurn - registers the host with the given turn server
  520. func RegisterHostWithTurn(hostID, hostPass string) error {
  521. auth := servercfg.GetTurnUserName() + ":" + servercfg.GetTurnPassword()
  522. api := httpclient.JSONEndpoint[models.SuccessResponse, models.ErrorResponse]{
  523. URL: servercfg.GetTurnApiHost(),
  524. Route: "/api/v1/host/register",
  525. Method: http.MethodPost,
  526. Authorization: fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(auth))),
  527. Data: models.HostTurnRegister{
  528. HostID: hostID,
  529. HostPassHash: ConvHostPassToHash(hostPass),
  530. },
  531. Response: models.SuccessResponse{},
  532. ErrorResponse: models.ErrorResponse{},
  533. }
  534. _, errData, err := api.GetJSON(models.SuccessResponse{}, models.ErrorResponse{})
  535. if err != nil {
  536. if errors.Is(err, httpclient.ErrStatus) {
  537. logger.Log(1, "error server status", strconv.Itoa(errData.Code), errData.Message)
  538. }
  539. return err
  540. }
  541. return nil
  542. }
  543. // DeRegisterHostWithTurn - to be called when host need to be deregistered from a turn server
  544. func DeRegisterHostWithTurn(hostID string) error {
  545. auth := servercfg.GetTurnUserName() + ":" + servercfg.GetTurnPassword()
  546. api := httpclient.JSONEndpoint[models.SuccessResponse, models.ErrorResponse]{
  547. URL: servercfg.GetTurnApiHost(),
  548. Route: fmt.Sprintf("/api/v1/host/deregister?host_id=%s", hostID),
  549. Method: http.MethodPost,
  550. Authorization: fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(auth))),
  551. Response: models.SuccessResponse{},
  552. ErrorResponse: models.ErrorResponse{},
  553. }
  554. _, errData, err := api.GetJSON(models.SuccessResponse{}, models.ErrorResponse{})
  555. if err != nil {
  556. if errors.Is(err, httpclient.ErrStatus) {
  557. logger.Log(1, "error server status", strconv.Itoa(errData.Code), errData.Message)
  558. }
  559. return err
  560. }
  561. return nil
  562. }
  563. // SortApiHosts - Sorts slice of ApiHosts by their ID alphabetically with numbers first
  564. func SortApiHosts(unsortedHosts []models.ApiHost) {
  565. sort.Slice(unsortedHosts, func(i, j int) bool {
  566. return unsortedHosts[i].ID < unsortedHosts[j].ID
  567. })
  568. }