hosts.go 13 KB

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