hosts.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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. "github.com/gravitl/netmaker/database"
  15. "github.com/gravitl/netmaker/logger"
  16. "github.com/gravitl/netmaker/models"
  17. "github.com/gravitl/netmaker/servercfg"
  18. "golang.org/x/crypto/bcrypt"
  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, err := GetAllHosts()
  142. if err != nil && !database.IsEmptyRecord(err) {
  143. return err
  144. }
  145. if len(hosts) >= Hosts_Limit {
  146. return errors.New("free tier limits exceeded on hosts")
  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.InternetGateway = currentHost.InternetGateway
  180. newHost.TrafficKeyPublic = currentHost.TrafficKeyPublic
  181. // changeable fields
  182. if len(newHost.Version) == 0 {
  183. newHost.Version = currentHost.Version
  184. }
  185. if len(newHost.Name) == 0 {
  186. newHost.Name = currentHost.Name
  187. }
  188. if newHost.MTU == 0 {
  189. newHost.MTU = currentHost.MTU
  190. }
  191. if newHost.ListenPort == 0 {
  192. newHost.ListenPort = currentHost.ListenPort
  193. }
  194. }
  195. // UpdateHostFromClient - used for updating host on server with update recieved from client
  196. func UpdateHostFromClient(newHost, currHost *models.Host) (sendPeerUpdate bool) {
  197. if newHost.PublicKey != currHost.PublicKey {
  198. currHost.PublicKey = newHost.PublicKey
  199. sendPeerUpdate = true
  200. }
  201. if newHost.ListenPort != 0 && currHost.ListenPort != newHost.ListenPort {
  202. currHost.ListenPort = newHost.ListenPort
  203. sendPeerUpdate = true
  204. }
  205. if newHost.WgPublicListenPort != 0 && currHost.WgPublicListenPort != newHost.WgPublicListenPort {
  206. currHost.WgPublicListenPort = newHost.WgPublicListenPort
  207. sendPeerUpdate = true
  208. }
  209. if currHost.EndpointIP.String() != newHost.EndpointIP.String() {
  210. currHost.EndpointIP = newHost.EndpointIP
  211. sendPeerUpdate = true
  212. }
  213. currHost.DaemonInstalled = newHost.DaemonInstalled
  214. currHost.Debug = newHost.Debug
  215. currHost.Verbosity = newHost.Verbosity
  216. currHost.Version = newHost.Version
  217. if newHost.Name != "" {
  218. currHost.Name = newHost.Name
  219. }
  220. if len(newHost.NatType) > 0 && newHost.NatType != currHost.NatType {
  221. currHost.NatType = newHost.NatType
  222. sendPeerUpdate = true
  223. }
  224. return
  225. }
  226. // UpsertHost - upserts into DB a given host model, does not check for existence*
  227. func UpsertHost(h *models.Host) error {
  228. data, err := json.Marshal(h)
  229. if err != nil {
  230. return err
  231. }
  232. err = database.Insert(h.ID.String(), string(data), database.HOSTS_TABLE_NAME)
  233. if err != nil {
  234. return err
  235. }
  236. storeHostInCache(*h)
  237. return nil
  238. }
  239. // RemoveHost - removes a given host from server
  240. func RemoveHost(h *models.Host, forceDelete bool) error {
  241. if !forceDelete && len(h.Nodes) > 0 {
  242. return fmt.Errorf("host still has associated nodes")
  243. }
  244. if servercfg.IsUsingTurn() {
  245. DeRegisterHostWithTurn(h.ID.String())
  246. }
  247. if len(h.Nodes) > 0 {
  248. if err := DisassociateAllNodesFromHost(h.ID.String()); err != nil {
  249. return err
  250. }
  251. }
  252. err := database.DeleteRecord(database.HOSTS_TABLE_NAME, h.ID.String())
  253. if err != nil {
  254. return err
  255. }
  256. deleteHostFromCache(h.ID.String())
  257. return nil
  258. }
  259. // RemoveHostByID - removes a given host by id from server
  260. func RemoveHostByID(hostID string) error {
  261. if servercfg.IsUsingTurn() {
  262. DeRegisterHostWithTurn(hostID)
  263. }
  264. err := database.DeleteRecord(database.HOSTS_TABLE_NAME, hostID)
  265. if err != nil {
  266. return err
  267. }
  268. deleteHostFromCache(hostID)
  269. return nil
  270. }
  271. // UpdateHostNetwork - adds/deletes host from a network
  272. func UpdateHostNetwork(h *models.Host, network string, add bool) (*models.Node, error) {
  273. for _, nodeID := range h.Nodes {
  274. node, err := GetNodeByID(nodeID)
  275. if err != nil || node.PendingDelete {
  276. continue
  277. }
  278. if node.Network == network {
  279. if !add {
  280. return &node, nil
  281. } else {
  282. return nil, errors.New("host already part of network " + network)
  283. }
  284. }
  285. }
  286. if !add {
  287. return nil, errors.New("host not part of the network " + network)
  288. } else {
  289. newNode := models.Node{}
  290. newNode.Server = servercfg.GetServer()
  291. newNode.Network = network
  292. newNode.HostID = h.ID
  293. if err := AssociateNodeToHost(&newNode, h); err != nil {
  294. return nil, err
  295. }
  296. return &newNode, nil
  297. }
  298. }
  299. // AssociateNodeToHost - associates and creates a node with a given host
  300. // should be the only way nodes get created as of 0.18
  301. func AssociateNodeToHost(n *models.Node, h *models.Host) error {
  302. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  303. return ErrInvalidHostID
  304. }
  305. n.HostID = h.ID
  306. err := createNode(n)
  307. if err != nil {
  308. return err
  309. }
  310. currentHost, err := GetHost(h.ID.String())
  311. if err != nil {
  312. return err
  313. }
  314. h.HostPass = currentHost.HostPass
  315. h.Nodes = append(currentHost.Nodes, n.ID.String())
  316. return UpsertHost(h)
  317. }
  318. // DissasociateNodeFromHost - deletes a node and removes from host nodes
  319. // should be the only way nodes are deleted as of 0.18
  320. func DissasociateNodeFromHost(n *models.Node, h *models.Host) error {
  321. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  322. return ErrInvalidHostID
  323. }
  324. if n.HostID != h.ID { // check if node actually belongs to host
  325. return fmt.Errorf("node is not associated with host")
  326. }
  327. if len(h.Nodes) == 0 {
  328. return fmt.Errorf("no nodes present in given host")
  329. }
  330. index := -1
  331. for i := range h.Nodes {
  332. if h.Nodes[i] == n.ID.String() {
  333. index = i
  334. break
  335. }
  336. }
  337. if index < 0 {
  338. if len(h.Nodes) == 0 {
  339. return fmt.Errorf("node %s, not found in host, %s", n.ID.String(), h.ID.String())
  340. }
  341. } else {
  342. h.Nodes = RemoveStringSlice(h.Nodes, index)
  343. }
  344. go func() {
  345. if servercfg.Is_EE {
  346. if clients, err := GetNetworkExtClients(n.Network); err != nil {
  347. for i := range clients {
  348. AllowClientNodeAccess(&clients[i], n.ID.String())
  349. }
  350. }
  351. }
  352. }()
  353. if err := deleteNodeByID(n); err != nil {
  354. return err
  355. }
  356. return UpsertHost(h)
  357. }
  358. // DisassociateAllNodesFromHost - deletes all nodes of the host
  359. func DisassociateAllNodesFromHost(hostID string) error {
  360. host, err := GetHost(hostID)
  361. if err != nil {
  362. return err
  363. }
  364. for _, nodeID := range host.Nodes {
  365. node, err := GetNodeByID(nodeID)
  366. if err != nil {
  367. logger.Log(0, "failed to get host node", err.Error())
  368. continue
  369. }
  370. if err := DeleteNode(&node, true); err != nil {
  371. logger.Log(0, "failed to delete node", node.ID.String(), err.Error())
  372. continue
  373. }
  374. logger.Log(3, "deleted node", node.ID.String(), "of host", host.ID.String())
  375. }
  376. host.Nodes = []string{}
  377. return UpsertHost(host)
  378. }
  379. // GetDefaultHosts - retrieve all hosts marked as default from DB
  380. func GetDefaultHosts() []models.Host {
  381. defaultHostList := []models.Host{}
  382. hosts, err := GetAllHosts()
  383. if err != nil {
  384. return defaultHostList
  385. }
  386. for i := range hosts {
  387. if hosts[i].IsDefault {
  388. defaultHostList = append(defaultHostList, hosts[i])
  389. }
  390. }
  391. return defaultHostList[:]
  392. }
  393. // GetHostNetworks - fetches all the networks
  394. func GetHostNetworks(hostID string) []string {
  395. currHost, err := GetHost(hostID)
  396. if err != nil {
  397. return nil
  398. }
  399. nets := []string{}
  400. for i := range currHost.Nodes {
  401. n, err := GetNodeByID(currHost.Nodes[i])
  402. if err != nil {
  403. return nil
  404. }
  405. nets = append(nets, n.Network)
  406. }
  407. return nets
  408. }
  409. // GetRelatedHosts - fetches related hosts of a given host
  410. func GetRelatedHosts(hostID string) []models.Host {
  411. relatedHosts := []models.Host{}
  412. networks := GetHostNetworks(hostID)
  413. networkMap := make(map[string]struct{})
  414. for _, network := range networks {
  415. networkMap[network] = struct{}{}
  416. }
  417. hosts, err := GetAllHosts()
  418. if err == nil {
  419. for _, host := range hosts {
  420. if host.ID.String() == hostID {
  421. continue
  422. }
  423. networks := GetHostNetworks(host.ID.String())
  424. for _, network := range networks {
  425. if _, ok := networkMap[network]; ok {
  426. relatedHosts = append(relatedHosts, host)
  427. break
  428. }
  429. }
  430. }
  431. }
  432. return relatedHosts
  433. }
  434. // CheckHostPort checks host endpoints to ensures that hosts on the same server
  435. // with the same endpoint have different listen ports
  436. // in the case of 64535 hosts or more with same endpoint, ports will not be changed
  437. func CheckHostPorts(h *models.Host) {
  438. portsInUse := make(map[int]bool, 0)
  439. hosts, err := GetAllHosts()
  440. if err != nil {
  441. return
  442. }
  443. for _, host := range hosts {
  444. if host.ID.String() == h.ID.String() {
  445. //skip self
  446. continue
  447. }
  448. if !host.EndpointIP.Equal(h.EndpointIP) {
  449. continue
  450. }
  451. portsInUse[host.ListenPort] = true
  452. }
  453. // iterate until port is not found or max iteration is reached
  454. for i := 0; portsInUse[h.ListenPort] && i < maxPort-minPort+1; i++ {
  455. h.ListenPort++
  456. if h.ListenPort > maxPort {
  457. h.ListenPort = minPort
  458. }
  459. }
  460. }
  461. // HostExists - checks if given host already exists
  462. func HostExists(h *models.Host) bool {
  463. _, err := GetHost(h.ID.String())
  464. return (err != nil && !database.IsEmptyRecord(err)) || (err == nil)
  465. }
  466. // GetHostByNodeID - returns a host if found to have a node's ID, else nil
  467. func GetHostByNodeID(id string) *models.Host {
  468. hosts, err := GetAllHosts()
  469. if err != nil {
  470. return nil
  471. }
  472. for i := range hosts {
  473. h := hosts[i]
  474. if StringSliceContains(h.Nodes, id) {
  475. return &h
  476. }
  477. }
  478. return nil
  479. }
  480. // ConvHostPassToHash - converts password to md5 hash
  481. func ConvHostPassToHash(hostPass string) string {
  482. return fmt.Sprintf("%x", md5.Sum([]byte(hostPass)))
  483. }
  484. // RegisterHostWithTurn - registers the host with the given turn server
  485. func RegisterHostWithTurn(hostID, hostPass string) error {
  486. auth := servercfg.GetTurnUserName() + ":" + servercfg.GetTurnPassword()
  487. api := httpclient.JSONEndpoint[models.SuccessResponse, models.ErrorResponse]{
  488. URL: servercfg.GetTurnApiHost(),
  489. Route: "/api/v1/host/register",
  490. Method: http.MethodPost,
  491. Authorization: fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(auth))),
  492. Data: models.HostTurnRegister{
  493. HostID: hostID,
  494. HostPassHash: ConvHostPassToHash(hostPass),
  495. },
  496. Response: models.SuccessResponse{},
  497. ErrorResponse: models.ErrorResponse{},
  498. }
  499. _, errData, err := api.GetJSON(models.SuccessResponse{}, models.ErrorResponse{})
  500. if err != nil {
  501. if errors.Is(err, httpclient.ErrStatus) {
  502. logger.Log(1, "error server status", strconv.Itoa(errData.Code), errData.Message)
  503. }
  504. return err
  505. }
  506. return nil
  507. }
  508. // DeRegisterHostWithTurn - to be called when host need to be deregistered from a turn server
  509. func DeRegisterHostWithTurn(hostID string) error {
  510. auth := servercfg.GetTurnUserName() + ":" + servercfg.GetTurnPassword()
  511. api := httpclient.JSONEndpoint[models.SuccessResponse, models.ErrorResponse]{
  512. URL: servercfg.GetTurnApiHost(),
  513. Route: fmt.Sprintf("/api/v1/host/deregister?host_id=%s", hostID),
  514. Method: http.MethodPost,
  515. Authorization: fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(auth))),
  516. Response: models.SuccessResponse{},
  517. ErrorResponse: models.ErrorResponse{},
  518. }
  519. _, errData, err := api.GetJSON(models.SuccessResponse{}, models.ErrorResponse{})
  520. if err != nil {
  521. if errors.Is(err, httpclient.ErrStatus) {
  522. logger.Log(1, "error server status", strconv.Itoa(errData.Code), errData.Message)
  523. }
  524. return err
  525. }
  526. return nil
  527. }
  528. // SortApiHosts - Sorts slice of ApiHosts by their ID alphabetically with numbers first
  529. func SortApiHosts(unsortedHosts []models.ApiHost) {
  530. sort.Slice(unsortedHosts, func(i, j int) bool {
  531. return unsortedHosts[i].ID < unsortedHosts[j].ID
  532. })
  533. }