hosts.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. package logic
  2. import (
  3. "crypto/md5"
  4. "encoding/base64"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "log"
  9. "net/http"
  10. "sort"
  11. "strconv"
  12. "sync"
  13. "github.com/devilcove/httpclient"
  14. "github.com/google/uuid"
  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. "golang.org/x/crypto/bcrypt"
  20. )
  21. var (
  22. hostCacheMutex = &sync.RWMutex{}
  23. hostsCacheMap = make(map[string]models.Host)
  24. )
  25. var (
  26. // ErrHostExists error indicating that host exists when trying to create new host
  27. ErrHostExists error = errors.New("host already exists")
  28. // ErrInvalidHostID
  29. ErrInvalidHostID error = errors.New("invalid host id")
  30. )
  31. func getHostsFromCache() (hosts []models.Host) {
  32. hostCacheMutex.RLock()
  33. for _, host := range hostsCacheMap {
  34. hosts = append(hosts, host)
  35. }
  36. hostCacheMutex.RUnlock()
  37. return
  38. }
  39. func getHostsMapFromCache() (hostsMap map[string]models.Host) {
  40. hostCacheMutex.RLock()
  41. hostsMap = hostsCacheMap
  42. hostCacheMutex.RUnlock()
  43. return
  44. }
  45. func getHostFromCache(hostID string) (host models.Host, ok bool) {
  46. hostCacheMutex.RLock()
  47. host, ok = hostsCacheMap[hostID]
  48. hostCacheMutex.RUnlock()
  49. return
  50. }
  51. func storeHostInCache(h models.Host) {
  52. hostCacheMutex.Lock()
  53. hostsCacheMap[h.ID.String()] = h
  54. hostCacheMutex.Unlock()
  55. }
  56. func deleteHostFromCache(hostID string) {
  57. hostCacheMutex.Lock()
  58. delete(hostsCacheMap, hostID)
  59. hostCacheMutex.Unlock()
  60. }
  61. func loadHostsIntoCache(hMap map[string]models.Host) {
  62. hostCacheMutex.Lock()
  63. hostsCacheMap = hMap
  64. hostCacheMutex.Unlock()
  65. }
  66. const (
  67. maxPort = 1<<16 - 1
  68. minPort = 1025
  69. )
  70. // GetAllHosts - returns all hosts in flat list or error
  71. func GetAllHosts() ([]models.Host, error) {
  72. currHosts := getHostsFromCache()
  73. if len(currHosts) != 0 {
  74. return currHosts, nil
  75. }
  76. records, err := database.FetchRecords(database.HOSTS_TABLE_NAME)
  77. if err != nil && !database.IsEmptyRecord(err) {
  78. return nil, err
  79. }
  80. currHostsMap := make(map[string]models.Host)
  81. defer loadHostsIntoCache(currHostsMap)
  82. for k := range records {
  83. var h models.Host
  84. err = json.Unmarshal([]byte(records[k]), &h)
  85. if err != nil {
  86. return nil, err
  87. }
  88. currHosts = append(currHosts, h)
  89. currHostsMap[h.ID.String()] = h
  90. }
  91. return currHosts, nil
  92. }
  93. // GetAllHostsAPI - get's all the hosts in an API usable format
  94. func GetAllHostsAPI(hosts []models.Host) []models.ApiHost {
  95. apiHosts := []models.ApiHost{}
  96. for i := range hosts {
  97. newApiHost := hosts[i].ConvertNMHostToAPI()
  98. apiHosts = append(apiHosts, *newApiHost)
  99. }
  100. return apiHosts[:]
  101. }
  102. // GetHostsMap - gets all the current hosts on machine in a map
  103. func GetHostsMap() (map[string]models.Host, error) {
  104. hostsMap := getHostsMapFromCache()
  105. if len(hostsMap) != 0 {
  106. return hostsMap, nil
  107. }
  108. records, err := database.FetchRecords(database.HOSTS_TABLE_NAME)
  109. if err != nil && !database.IsEmptyRecord(err) {
  110. return nil, err
  111. }
  112. currHostMap := make(map[string]models.Host)
  113. defer loadHostsIntoCache(currHostMap)
  114. for k := range records {
  115. var h models.Host
  116. err = json.Unmarshal([]byte(records[k]), &h)
  117. if err != nil {
  118. return nil, err
  119. }
  120. currHostMap[h.ID.String()] = h
  121. }
  122. return currHostMap, nil
  123. }
  124. // GetHost - gets a host from db given id
  125. func GetHost(hostid string) (*models.Host, error) {
  126. if host, ok := getHostFromCache(hostid); ok {
  127. return &host, nil
  128. }
  129. record, err := database.FetchRecord(database.HOSTS_TABLE_NAME, hostid)
  130. if err != nil {
  131. return nil, err
  132. }
  133. var h models.Host
  134. if err = json.Unmarshal([]byte(record), &h); err != nil {
  135. return nil, err
  136. }
  137. storeHostInCache(h)
  138. return &h, nil
  139. }
  140. // CreateHost - creates a host if not exist
  141. func CreateHost(h *models.Host) error {
  142. hosts, err := GetAllHosts()
  143. if err != nil && !database.IsEmptyRecord(err) {
  144. return err
  145. }
  146. if len(hosts) >= Hosts_Limit {
  147. return errors.New("free tier limits exceeded on hosts")
  148. }
  149. _, err = GetHost(h.ID.String())
  150. if (err != nil && !database.IsEmptyRecord(err)) || (err == nil) {
  151. return ErrHostExists
  152. }
  153. if servercfg.IsUsingTurn() {
  154. err = RegisterHostWithTurn(h.ID.String(), h.HostPass)
  155. if err != nil {
  156. logger.Log(0, "failed to register host with turn server: ", err.Error())
  157. }
  158. }
  159. // encrypt that password so we never see it
  160. hash, err := bcrypt.GenerateFromPassword([]byte(h.HostPass), 5)
  161. if err != nil {
  162. return err
  163. }
  164. h.HostPass = string(hash)
  165. h.AutoUpdate = servercfg.AutoUpdateEnabled()
  166. // if another server has already updated proxyenabled, leave it alone
  167. if !h.ProxyEnabledSet {
  168. log.Println("checking default proxy", servercfg.GetServerConfig().DefaultProxyMode)
  169. if servercfg.GetServerConfig().DefaultProxyMode.Set {
  170. h.ProxyEnabledSet = true
  171. h.ProxyEnabled = servercfg.GetServerConfig().DefaultProxyMode.Value
  172. log.Println("set proxy enabled to ", h.ProxyEnabled)
  173. }
  174. }
  175. checkForZombieHosts(h)
  176. return UpsertHost(h)
  177. }
  178. // UpdateHost - updates host data by field
  179. func UpdateHost(newHost, currentHost *models.Host) {
  180. // unchangeable fields via API here
  181. newHost.DaemonInstalled = currentHost.DaemonInstalled
  182. newHost.OS = currentHost.OS
  183. newHost.IPForwarding = currentHost.IPForwarding
  184. newHost.HostPass = currentHost.HostPass
  185. newHost.MacAddress = currentHost.MacAddress
  186. newHost.Debug = currentHost.Debug
  187. newHost.Nodes = currentHost.Nodes
  188. newHost.PublicKey = currentHost.PublicKey
  189. newHost.InternetGateway = currentHost.InternetGateway
  190. newHost.TrafficKeyPublic = currentHost.TrafficKeyPublic
  191. // changeable fields
  192. if len(newHost.Version) == 0 {
  193. newHost.Version = currentHost.Version
  194. }
  195. if len(newHost.Name) == 0 {
  196. newHost.Name = currentHost.Name
  197. }
  198. if newHost.MTU == 0 {
  199. newHost.MTU = currentHost.MTU
  200. }
  201. if newHost.ListenPort == 0 {
  202. newHost.ListenPort = currentHost.ListenPort
  203. }
  204. if newHost.ProxyListenPort == 0 {
  205. newHost.ProxyListenPort = currentHost.ProxyListenPort
  206. }
  207. newHost.PublicListenPort = currentHost.PublicListenPort
  208. }
  209. // UpdateHostFromClient - used for updating host on server with update recieved from client
  210. func UpdateHostFromClient(newHost, currHost *models.Host) (sendPeerUpdate bool) {
  211. if newHost.PublicKey != currHost.PublicKey {
  212. currHost.PublicKey = newHost.PublicKey
  213. sendPeerUpdate = true
  214. }
  215. if newHost.ListenPort != 0 && currHost.ListenPort != newHost.ListenPort {
  216. currHost.ListenPort = newHost.ListenPort
  217. sendPeerUpdate = true
  218. }
  219. if newHost.WgPublicListenPort != 0 && currHost.WgPublicListenPort != newHost.WgPublicListenPort {
  220. currHost.WgPublicListenPort = newHost.WgPublicListenPort
  221. sendPeerUpdate = true
  222. }
  223. if newHost.ProxyListenPort != 0 && currHost.ProxyListenPort != newHost.ProxyListenPort {
  224. currHost.ProxyListenPort = newHost.ProxyListenPort
  225. sendPeerUpdate = true
  226. }
  227. if newHost.PublicListenPort != 0 && currHost.PublicListenPort != newHost.PublicListenPort {
  228. currHost.PublicListenPort = newHost.PublicListenPort
  229. sendPeerUpdate = true
  230. }
  231. if currHost.ProxyEnabled != newHost.ProxyEnabled {
  232. currHost.ProxyEnabled = newHost.ProxyEnabled
  233. sendPeerUpdate = true
  234. }
  235. if currHost.EndpointIP.String() != newHost.EndpointIP.String() {
  236. currHost.EndpointIP = newHost.EndpointIP
  237. sendPeerUpdate = true
  238. }
  239. currHost.DaemonInstalled = newHost.DaemonInstalled
  240. currHost.Debug = newHost.Debug
  241. currHost.Verbosity = newHost.Verbosity
  242. currHost.Version = newHost.Version
  243. if newHost.Name != "" {
  244. currHost.Name = newHost.Name
  245. }
  246. if len(newHost.NatType) > 0 && newHost.NatType != currHost.NatType {
  247. currHost.NatType = newHost.NatType
  248. sendPeerUpdate = true
  249. }
  250. return
  251. }
  252. // UpsertHost - upserts into DB a given host model, does not check for existence*
  253. func UpsertHost(h *models.Host) error {
  254. data, err := json.Marshal(h)
  255. if err != nil {
  256. return err
  257. }
  258. err = database.Insert(h.ID.String(), string(data), database.HOSTS_TABLE_NAME)
  259. if err != nil {
  260. return err
  261. }
  262. storeHostInCache(*h)
  263. return nil
  264. }
  265. // RemoveHost - removes a given host from server
  266. func RemoveHost(h *models.Host, forceDelete bool) error {
  267. if !forceDelete && len(h.Nodes) > 0 {
  268. return fmt.Errorf("host still has associated nodes")
  269. }
  270. if servercfg.IsUsingTurn() {
  271. DeRegisterHostWithTurn(h.ID.String())
  272. }
  273. if len(h.Nodes) > 0 {
  274. if err := DisassociateAllNodesFromHost(h.ID.String()); err != nil {
  275. return err
  276. }
  277. }
  278. err := database.DeleteRecord(database.HOSTS_TABLE_NAME, h.ID.String())
  279. if err != nil {
  280. return err
  281. }
  282. deleteHostFromCache(h.ID.String())
  283. return nil
  284. }
  285. // RemoveHostByID - removes a given host by id from server
  286. func RemoveHostByID(hostID string) error {
  287. if servercfg.IsUsingTurn() {
  288. DeRegisterHostWithTurn(hostID)
  289. }
  290. err := database.DeleteRecord(database.HOSTS_TABLE_NAME, hostID)
  291. if err != nil {
  292. return err
  293. }
  294. deleteHostFromCache(hostID)
  295. return nil
  296. }
  297. // UpdateHostNetwork - adds/deletes host from a network
  298. func UpdateHostNetwork(h *models.Host, network string, add bool) (*models.Node, error) {
  299. for _, nodeID := range h.Nodes {
  300. node, err := GetNodeByID(nodeID)
  301. if err != nil || node.PendingDelete {
  302. continue
  303. }
  304. if node.Network == network {
  305. if !add {
  306. return &node, nil
  307. } else {
  308. return nil, errors.New("host already part of network " + network)
  309. }
  310. }
  311. }
  312. if !add {
  313. return nil, errors.New("host not part of the network " + network)
  314. } else {
  315. newNode := models.Node{}
  316. newNode.Server = servercfg.GetServer()
  317. newNode.Network = network
  318. newNode.HostID = h.ID
  319. if err := AssociateNodeToHost(&newNode, h); err != nil {
  320. return nil, err
  321. }
  322. return &newNode, nil
  323. }
  324. }
  325. // AssociateNodeToHost - associates and creates a node with a given host
  326. // should be the only way nodes get created as of 0.18
  327. func AssociateNodeToHost(n *models.Node, h *models.Host) error {
  328. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  329. return ErrInvalidHostID
  330. }
  331. n.HostID = h.ID
  332. err := createNode(n)
  333. if err != nil {
  334. return err
  335. }
  336. currentHost, err := GetHost(h.ID.String())
  337. if err != nil {
  338. return err
  339. }
  340. h.HostPass = currentHost.HostPass
  341. h.Nodes = append(currentHost.Nodes, n.ID.String())
  342. return UpsertHost(h)
  343. }
  344. // DissasociateNodeFromHost - deletes a node and removes from host nodes
  345. // should be the only way nodes are deleted as of 0.18
  346. func DissasociateNodeFromHost(n *models.Node, h *models.Host) error {
  347. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  348. return ErrInvalidHostID
  349. }
  350. if n.HostID != h.ID { // check if node actually belongs to host
  351. return fmt.Errorf("node is not associated with host")
  352. }
  353. if len(h.Nodes) == 0 {
  354. return fmt.Errorf("no nodes present in given host")
  355. }
  356. index := -1
  357. for i := range h.Nodes {
  358. if h.Nodes[i] == n.ID.String() {
  359. index = i
  360. break
  361. }
  362. }
  363. if index < 0 {
  364. if len(h.Nodes) == 0 {
  365. return fmt.Errorf("node %s, not found in host, %s", n.ID.String(), h.ID.String())
  366. }
  367. } else {
  368. h.Nodes = RemoveStringSlice(h.Nodes, index)
  369. }
  370. go func() {
  371. if servercfg.Is_EE {
  372. if clients, err := GetNetworkExtClients(n.Network); err != nil {
  373. for i := range clients {
  374. AllowClientNodeAccess(&clients[i], n.ID.String())
  375. }
  376. }
  377. }
  378. }()
  379. if err := deleteNodeByID(n); err != nil {
  380. return err
  381. }
  382. return UpsertHost(h)
  383. }
  384. // DisassociateAllNodesFromHost - deletes all nodes of the host
  385. func DisassociateAllNodesFromHost(hostID string) error {
  386. host, err := GetHost(hostID)
  387. if err != nil {
  388. return err
  389. }
  390. for _, nodeID := range host.Nodes {
  391. node, err := GetNodeByID(nodeID)
  392. if err != nil {
  393. logger.Log(0, "failed to get host node", err.Error())
  394. continue
  395. }
  396. if err := DeleteNode(&node, true); err != nil {
  397. logger.Log(0, "failed to delete node", node.ID.String(), err.Error())
  398. continue
  399. }
  400. logger.Log(3, "deleted node", node.ID.String(), "of host", host.ID.String())
  401. }
  402. host.Nodes = []string{}
  403. return UpsertHost(host)
  404. }
  405. // GetDefaultHosts - retrieve all hosts marked as default from DB
  406. func GetDefaultHosts() []models.Host {
  407. defaultHostList := []models.Host{}
  408. hosts, err := GetAllHosts()
  409. if err != nil {
  410. return defaultHostList
  411. }
  412. for i := range hosts {
  413. if hosts[i].IsDefault {
  414. defaultHostList = append(defaultHostList, hosts[i])
  415. }
  416. }
  417. return defaultHostList[:]
  418. }
  419. // GetHostNetworks - fetches all the networks
  420. func GetHostNetworks(hostID string) []string {
  421. currHost, err := GetHost(hostID)
  422. if err != nil {
  423. return nil
  424. }
  425. nets := []string{}
  426. for i := range currHost.Nodes {
  427. n, err := GetNodeByID(currHost.Nodes[i])
  428. if err != nil {
  429. return nil
  430. }
  431. nets = append(nets, n.Network)
  432. }
  433. return nets
  434. }
  435. // GetRelatedHosts - fetches related hosts of a given host
  436. func GetRelatedHosts(hostID string) []models.Host {
  437. relatedHosts := []models.Host{}
  438. networks := GetHostNetworks(hostID)
  439. networkMap := make(map[string]struct{})
  440. for _, network := range networks {
  441. networkMap[network] = struct{}{}
  442. }
  443. hosts, err := GetAllHosts()
  444. if err == nil {
  445. for _, host := range hosts {
  446. if host.ID.String() == hostID {
  447. continue
  448. }
  449. networks := GetHostNetworks(host.ID.String())
  450. for _, network := range networks {
  451. if _, ok := networkMap[network]; ok {
  452. relatedHosts = append(relatedHosts, host)
  453. break
  454. }
  455. }
  456. }
  457. }
  458. return relatedHosts
  459. }
  460. // CheckHostPort checks host endpoints to ensures that hosts on the same server
  461. // with the same endpoint have different listen ports
  462. // in the case of 64535 hosts or more with same endpoint, ports will not be changed
  463. func CheckHostPorts(h *models.Host) {
  464. portsInUse := make(map[int]bool, 0)
  465. hosts, err := GetAllHosts()
  466. if err != nil {
  467. return
  468. }
  469. for _, host := range hosts {
  470. if host.ID.String() == h.ID.String() {
  471. //skip self
  472. continue
  473. }
  474. if !host.EndpointIP.Equal(h.EndpointIP) {
  475. continue
  476. }
  477. portsInUse[host.ListenPort] = true
  478. portsInUse[host.ProxyListenPort] = true
  479. }
  480. // iterate until port is not found or max iteration is reached
  481. for i := 0; portsInUse[h.ListenPort] && i < maxPort-minPort+1; i++ {
  482. h.ListenPort++
  483. if h.ListenPort > maxPort {
  484. h.ListenPort = minPort
  485. }
  486. }
  487. // allocate h.ListenPort so it is unavailable to h.ProxyListenPort
  488. portsInUse[h.ListenPort] = true
  489. for i := 0; portsInUse[h.ProxyListenPort] && i < maxPort-minPort+1; i++ {
  490. h.ProxyListenPort++
  491. if h.ProxyListenPort > maxPort {
  492. h.ProxyListenPort = 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. }