hosts.go 15 KB

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