2
0

hosts.go 15 KB

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