hosts.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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) error {
  267. if 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. err := database.DeleteRecord(database.HOSTS_TABLE_NAME, h.ID.String())
  274. if err != nil {
  275. return err
  276. }
  277. deleteHostFromCache(h.ID.String())
  278. return nil
  279. }
  280. // RemoveHostByID - removes a given host by id from server
  281. func RemoveHostByID(hostID string) error {
  282. if servercfg.IsUsingTurn() {
  283. DeRegisterHostWithTurn(hostID)
  284. }
  285. err := database.DeleteRecord(database.HOSTS_TABLE_NAME, hostID)
  286. if err != nil {
  287. return err
  288. }
  289. deleteHostFromCache(hostID)
  290. return nil
  291. }
  292. // UpdateHostNetwork - adds/deletes host from a network
  293. func UpdateHostNetwork(h *models.Host, network string, add bool) (*models.Node, error) {
  294. for _, nodeID := range h.Nodes {
  295. node, err := GetNodeByID(nodeID)
  296. if err != nil || node.PendingDelete {
  297. continue
  298. }
  299. if node.Network == network {
  300. if !add {
  301. return &node, nil
  302. } else {
  303. return nil, errors.New("host already part of network " + network)
  304. }
  305. }
  306. }
  307. if !add {
  308. return nil, errors.New("host not part of the network " + network)
  309. } else {
  310. newNode := models.Node{}
  311. newNode.Server = servercfg.GetServer()
  312. newNode.Network = network
  313. newNode.HostID = h.ID
  314. if err := AssociateNodeToHost(&newNode, h); err != nil {
  315. return nil, err
  316. }
  317. return &newNode, nil
  318. }
  319. }
  320. // AssociateNodeToHost - associates and creates a node with a given host
  321. // should be the only way nodes get created as of 0.18
  322. func AssociateNodeToHost(n *models.Node, h *models.Host) error {
  323. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  324. return ErrInvalidHostID
  325. }
  326. n.HostID = h.ID
  327. err := createNode(n)
  328. if err != nil {
  329. return err
  330. }
  331. currentHost, err := GetHost(h.ID.String())
  332. if err != nil {
  333. return err
  334. }
  335. h.HostPass = currentHost.HostPass
  336. h.Nodes = append(currentHost.Nodes, n.ID.String())
  337. return UpsertHost(h)
  338. }
  339. // DissasociateNodeFromHost - deletes a node and removes from host nodes
  340. // should be the only way nodes are deleted as of 0.18
  341. func DissasociateNodeFromHost(n *models.Node, h *models.Host) error {
  342. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  343. return ErrInvalidHostID
  344. }
  345. if n.HostID != h.ID { // check if node actually belongs to host
  346. return fmt.Errorf("node is not associated with host")
  347. }
  348. if len(h.Nodes) == 0 {
  349. return fmt.Errorf("no nodes present in given host")
  350. }
  351. index := -1
  352. for i := range h.Nodes {
  353. if h.Nodes[i] == n.ID.String() {
  354. index = i
  355. break
  356. }
  357. }
  358. if index < 0 {
  359. if len(h.Nodes) == 0 {
  360. return fmt.Errorf("node %s, not found in host, %s", n.ID.String(), h.ID.String())
  361. }
  362. } else {
  363. h.Nodes = RemoveStringSlice(h.Nodes, index)
  364. }
  365. if err := deleteNodeByID(n); err != nil {
  366. return err
  367. }
  368. return UpsertHost(h)
  369. }
  370. // DisassociateAllNodesFromHost - deletes all nodes of the host
  371. func DisassociateAllNodesFromHost(hostID string) error {
  372. host, err := GetHost(hostID)
  373. if err != nil {
  374. return err
  375. }
  376. for _, nodeID := range host.Nodes {
  377. node, err := GetNodeByID(nodeID)
  378. if err != nil {
  379. logger.Log(0, "failed to get host node", err.Error())
  380. continue
  381. }
  382. if err := DeleteNode(&node, true); err != nil {
  383. logger.Log(0, "failed to delete node", node.ID.String(), err.Error())
  384. continue
  385. }
  386. logger.Log(3, "deleted node", node.ID.String(), "of host", host.ID.String())
  387. }
  388. host.Nodes = []string{}
  389. return UpsertHost(host)
  390. }
  391. // GetDefaultHosts - retrieve all hosts marked as default from DB
  392. func GetDefaultHosts() []models.Host {
  393. defaultHostList := []models.Host{}
  394. hosts, err := GetAllHosts()
  395. if err != nil {
  396. return defaultHostList
  397. }
  398. for i := range hosts {
  399. if hosts[i].IsDefault {
  400. defaultHostList = append(defaultHostList, hosts[i])
  401. }
  402. }
  403. return defaultHostList[:]
  404. }
  405. // GetHostNetworks - fetches all the networks
  406. func GetHostNetworks(hostID string) []string {
  407. currHost, err := GetHost(hostID)
  408. if err != nil {
  409. return nil
  410. }
  411. nets := []string{}
  412. for i := range currHost.Nodes {
  413. n, err := GetNodeByID(currHost.Nodes[i])
  414. if err != nil {
  415. return nil
  416. }
  417. nets = append(nets, n.Network)
  418. }
  419. return nets
  420. }
  421. // GetRelatedHosts - fetches related hosts of a given host
  422. func GetRelatedHosts(hostID string) []models.Host {
  423. relatedHosts := []models.Host{}
  424. networks := GetHostNetworks(hostID)
  425. networkMap := make(map[string]struct{})
  426. for _, network := range networks {
  427. networkMap[network] = struct{}{}
  428. }
  429. hosts, err := GetAllHosts()
  430. if err == nil {
  431. for _, host := range hosts {
  432. if host.ID.String() == hostID {
  433. continue
  434. }
  435. networks := GetHostNetworks(host.ID.String())
  436. for _, network := range networks {
  437. if _, ok := networkMap[network]; ok {
  438. relatedHosts = append(relatedHosts, host)
  439. break
  440. }
  441. }
  442. }
  443. }
  444. return relatedHosts
  445. }
  446. // CheckHostPort checks host endpoints to ensures that hosts on the same server
  447. // with the same endpoint have different listen ports
  448. // in the case of 64535 hosts or more with same endpoint, ports will not be changed
  449. func CheckHostPorts(h *models.Host) {
  450. portsInUse := make(map[int]bool, 0)
  451. hosts, err := GetAllHosts()
  452. if err != nil {
  453. return
  454. }
  455. for _, host := range hosts {
  456. if host.ID.String() == h.ID.String() {
  457. //skip self
  458. continue
  459. }
  460. if !host.EndpointIP.Equal(h.EndpointIP) {
  461. continue
  462. }
  463. portsInUse[host.ListenPort] = true
  464. portsInUse[host.ProxyListenPort] = true
  465. }
  466. // iterate until port is not found or max iteration is reached
  467. for i := 0; portsInUse[h.ListenPort] && i < maxPort-minPort+1; i++ {
  468. h.ListenPort++
  469. if h.ListenPort > maxPort {
  470. h.ListenPort = minPort
  471. }
  472. }
  473. // allocate h.ListenPort so it is unavailable to h.ProxyListenPort
  474. portsInUse[h.ListenPort] = true
  475. for i := 0; portsInUse[h.ProxyListenPort] && i < maxPort-minPort+1; i++ {
  476. h.ProxyListenPort++
  477. if h.ProxyListenPort > maxPort {
  478. h.ProxyListenPort = minPort
  479. }
  480. }
  481. }
  482. // HostExists - checks if given host already exists
  483. func HostExists(h *models.Host) bool {
  484. _, err := GetHost(h.ID.String())
  485. return (err != nil && !database.IsEmptyRecord(err)) || (err == nil)
  486. }
  487. // GetHostByNodeID - returns a host if found to have a node's ID, else nil
  488. func GetHostByNodeID(id string) *models.Host {
  489. hosts, err := GetAllHosts()
  490. if err != nil {
  491. return nil
  492. }
  493. for i := range hosts {
  494. h := hosts[i]
  495. if StringSliceContains(h.Nodes, id) {
  496. return &h
  497. }
  498. }
  499. return nil
  500. }
  501. // ConvHostPassToHash - converts password to md5 hash
  502. func ConvHostPassToHash(hostPass string) string {
  503. return fmt.Sprintf("%x", md5.Sum([]byte(hostPass)))
  504. }
  505. // RegisterHostWithTurn - registers the host with the given turn server
  506. func RegisterHostWithTurn(hostID, hostPass string) error {
  507. auth := servercfg.GetTurnUserName() + ":" + servercfg.GetTurnPassword()
  508. api := httpclient.JSONEndpoint[models.SuccessResponse, models.ErrorResponse]{
  509. URL: servercfg.GetTurnApiHost(),
  510. Route: "/api/v1/host/register",
  511. Method: http.MethodPost,
  512. Authorization: fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(auth))),
  513. Data: models.HostTurnRegister{
  514. HostID: hostID,
  515. HostPassHash: ConvHostPassToHash(hostPass),
  516. },
  517. Response: models.SuccessResponse{},
  518. ErrorResponse: models.ErrorResponse{},
  519. }
  520. _, errData, err := api.GetJSON(models.SuccessResponse{}, models.ErrorResponse{})
  521. if err != nil {
  522. if errors.Is(err, httpclient.ErrStatus) {
  523. logger.Log(1, "error server status", strconv.Itoa(errData.Code), errData.Message)
  524. }
  525. return err
  526. }
  527. return nil
  528. }
  529. // DeRegisterHostWithTurn - to be called when host need to be deregistered from a turn server
  530. func DeRegisterHostWithTurn(hostID string) error {
  531. auth := servercfg.GetTurnUserName() + ":" + servercfg.GetTurnPassword()
  532. api := httpclient.JSONEndpoint[models.SuccessResponse, models.ErrorResponse]{
  533. URL: servercfg.GetTurnApiHost(),
  534. Route: fmt.Sprintf("/api/v1/host/deregister?host_id=%s", hostID),
  535. Method: http.MethodPost,
  536. Authorization: fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(auth))),
  537. Response: models.SuccessResponse{},
  538. ErrorResponse: models.ErrorResponse{},
  539. }
  540. _, errData, err := api.GetJSON(models.SuccessResponse{}, models.ErrorResponse{})
  541. if err != nil {
  542. if errors.Is(err, httpclient.ErrStatus) {
  543. logger.Log(1, "error server status", strconv.Itoa(errData.Code), errData.Message)
  544. }
  545. return err
  546. }
  547. return nil
  548. }
  549. // SortApiHosts - Sorts slice of ApiHosts by their ID alphabetically with numbers first
  550. func SortApiHosts(unsortedHosts []models.ApiHost) {
  551. sort.Slice(unsortedHosts, func(i, j int) bool {
  552. return unsortedHosts[i].ID < unsortedHosts[j].ID
  553. })
  554. }