hosts.go 13 KB

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