hosts.go 15 KB

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