hosts.go 14 KB

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