hosts.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  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. if err := deleteNodeByID(n); err != nil {
  371. return err
  372. }
  373. return UpsertHost(h)
  374. }
  375. // DisassociateAllNodesFromHost - deletes all nodes of the host
  376. func DisassociateAllNodesFromHost(hostID string) error {
  377. host, err := GetHost(hostID)
  378. if err != nil {
  379. return err
  380. }
  381. for _, nodeID := range host.Nodes {
  382. node, err := GetNodeByID(nodeID)
  383. if err != nil {
  384. logger.Log(0, "failed to get host node", err.Error())
  385. continue
  386. }
  387. if err := DeleteNode(&node, true); err != nil {
  388. logger.Log(0, "failed to delete node", node.ID.String(), err.Error())
  389. continue
  390. }
  391. logger.Log(3, "deleted node", node.ID.String(), "of host", host.ID.String())
  392. }
  393. host.Nodes = []string{}
  394. return UpsertHost(host)
  395. }
  396. // GetDefaultHosts - retrieve all hosts marked as default from DB
  397. func GetDefaultHosts() []models.Host {
  398. defaultHostList := []models.Host{}
  399. hosts, err := GetAllHosts()
  400. if err != nil {
  401. return defaultHostList
  402. }
  403. for i := range hosts {
  404. if hosts[i].IsDefault {
  405. defaultHostList = append(defaultHostList, hosts[i])
  406. }
  407. }
  408. return defaultHostList[:]
  409. }
  410. // GetHostNetworks - fetches all the networks
  411. func GetHostNetworks(hostID string) []string {
  412. currHost, err := GetHost(hostID)
  413. if err != nil {
  414. return nil
  415. }
  416. nets := []string{}
  417. for i := range currHost.Nodes {
  418. n, err := GetNodeByID(currHost.Nodes[i])
  419. if err != nil {
  420. return nil
  421. }
  422. nets = append(nets, n.Network)
  423. }
  424. return nets
  425. }
  426. // GetRelatedHosts - fetches related hosts of a given host
  427. func GetRelatedHosts(hostID string) []models.Host {
  428. relatedHosts := []models.Host{}
  429. networks := GetHostNetworks(hostID)
  430. networkMap := make(map[string]struct{})
  431. for _, network := range networks {
  432. networkMap[network] = struct{}{}
  433. }
  434. hosts, err := GetAllHosts()
  435. if err == nil {
  436. for _, host := range hosts {
  437. if host.ID.String() == hostID {
  438. continue
  439. }
  440. networks := GetHostNetworks(host.ID.String())
  441. for _, network := range networks {
  442. if _, ok := networkMap[network]; ok {
  443. relatedHosts = append(relatedHosts, host)
  444. break
  445. }
  446. }
  447. }
  448. }
  449. return relatedHosts
  450. }
  451. // CheckHostPort checks host endpoints to ensures that hosts on the same server
  452. // with the same endpoint have different listen ports
  453. // in the case of 64535 hosts or more with same endpoint, ports will not be changed
  454. func CheckHostPorts(h *models.Host) {
  455. portsInUse := make(map[int]bool, 0)
  456. hosts, err := GetAllHosts()
  457. if err != nil {
  458. return
  459. }
  460. for _, host := range hosts {
  461. if host.ID.String() == h.ID.String() {
  462. //skip self
  463. continue
  464. }
  465. if !host.EndpointIP.Equal(h.EndpointIP) {
  466. continue
  467. }
  468. portsInUse[host.ListenPort] = true
  469. portsInUse[host.ProxyListenPort] = true
  470. }
  471. // iterate until port is not found or max iteration is reached
  472. for i := 0; portsInUse[h.ListenPort] && i < maxPort-minPort+1; i++ {
  473. h.ListenPort++
  474. if h.ListenPort > maxPort {
  475. h.ListenPort = minPort
  476. }
  477. }
  478. // allocate h.ListenPort so it is unavailable to h.ProxyListenPort
  479. portsInUse[h.ListenPort] = true
  480. for i := 0; portsInUse[h.ProxyListenPort] && i < maxPort-minPort+1; i++ {
  481. h.ProxyListenPort++
  482. if h.ProxyListenPort > maxPort {
  483. h.ProxyListenPort = minPort
  484. }
  485. }
  486. }
  487. // HostExists - checks if given host already exists
  488. func HostExists(h *models.Host) bool {
  489. _, err := GetHost(h.ID.String())
  490. return (err != nil && !database.IsEmptyRecord(err)) || (err == nil)
  491. }
  492. // GetHostByNodeID - returns a host if found to have a node's ID, else nil
  493. func GetHostByNodeID(id string) *models.Host {
  494. hosts, err := GetAllHosts()
  495. if err != nil {
  496. return nil
  497. }
  498. for i := range hosts {
  499. h := hosts[i]
  500. if StringSliceContains(h.Nodes, id) {
  501. return &h
  502. }
  503. }
  504. return nil
  505. }
  506. // ConvHostPassToHash - converts password to md5 hash
  507. func ConvHostPassToHash(hostPass string) string {
  508. return fmt.Sprintf("%x", md5.Sum([]byte(hostPass)))
  509. }
  510. // RegisterHostWithTurn - registers the host with the given turn server
  511. func RegisterHostWithTurn(hostID, hostPass string) error {
  512. auth := servercfg.GetTurnUserName() + ":" + servercfg.GetTurnPassword()
  513. api := httpclient.JSONEndpoint[models.SuccessResponse, models.ErrorResponse]{
  514. URL: servercfg.GetTurnApiHost(),
  515. Route: "/api/v1/host/register",
  516. Method: http.MethodPost,
  517. Authorization: fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(auth))),
  518. Data: models.HostTurnRegister{
  519. HostID: hostID,
  520. HostPassHash: ConvHostPassToHash(hostPass),
  521. },
  522. Response: models.SuccessResponse{},
  523. ErrorResponse: models.ErrorResponse{},
  524. }
  525. _, errData, err := api.GetJSON(models.SuccessResponse{}, models.ErrorResponse{})
  526. if err != nil {
  527. if errors.Is(err, httpclient.ErrStatus) {
  528. logger.Log(1, "error server status", strconv.Itoa(errData.Code), errData.Message)
  529. }
  530. return err
  531. }
  532. return nil
  533. }
  534. // DeRegisterHostWithTurn - to be called when host need to be deregistered from a turn server
  535. func DeRegisterHostWithTurn(hostID string) error {
  536. auth := servercfg.GetTurnUserName() + ":" + servercfg.GetTurnPassword()
  537. api := httpclient.JSONEndpoint[models.SuccessResponse, models.ErrorResponse]{
  538. URL: servercfg.GetTurnApiHost(),
  539. Route: fmt.Sprintf("/api/v1/host/deregister?host_id=%s", hostID),
  540. Method: http.MethodPost,
  541. Authorization: fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(auth))),
  542. Response: models.SuccessResponse{},
  543. ErrorResponse: models.ErrorResponse{},
  544. }
  545. _, errData, err := api.GetJSON(models.SuccessResponse{}, models.ErrorResponse{})
  546. if err != nil {
  547. if errors.Is(err, httpclient.ErrStatus) {
  548. logger.Log(1, "error server status", strconv.Itoa(errData.Code), errData.Message)
  549. }
  550. return err
  551. }
  552. return nil
  553. }
  554. // SortApiHosts - Sorts slice of ApiHosts by their ID alphabetically with numbers first
  555. func SortApiHosts(unsortedHosts []models.ApiHost) {
  556. sort.Slice(unsortedHosts, func(i, j int) bool {
  557. return unsortedHosts[i].ID < unsortedHosts[j].ID
  558. })
  559. }