hosts.go 15 KB

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