hosts.go 15 KB

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