hosts.go 15 KB

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