hosts.go 16 KB

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