hosts.go 15 KB

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