hosts.go 14 KB

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