hosts.go 14 KB

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