hosts.go 16 KB

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