hosts.go 14 KB

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