hosts.go 14 KB

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