hosts.go 14 KB

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