networks.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. package logic
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "sort"
  8. "strings"
  9. "github.com/c-robinson/iplib"
  10. validator "github.com/go-playground/validator/v10"
  11. "github.com/gravitl/netmaker/database"
  12. "github.com/gravitl/netmaker/logger"
  13. "github.com/gravitl/netmaker/logic/acls/nodeacls"
  14. "github.com/gravitl/netmaker/logic/pro"
  15. "github.com/gravitl/netmaker/models"
  16. "github.com/gravitl/netmaker/validation"
  17. )
  18. // GetNetworks - returns all networks from database
  19. func GetNetworks() ([]models.Network, error) {
  20. var networks []models.Network
  21. collection, err := database.FetchRecords(database.NETWORKS_TABLE_NAME)
  22. if err != nil {
  23. return networks, err
  24. }
  25. for _, value := range collection {
  26. var network models.Network
  27. if err := json.Unmarshal([]byte(value), &network); err != nil {
  28. return networks, err
  29. }
  30. // add network our array
  31. networks = append(networks, network)
  32. }
  33. return networks, err
  34. }
  35. // DeleteNetwork - deletes a network
  36. func DeleteNetwork(network string) error {
  37. // remove ACL for network
  38. err := nodeacls.DeleteACLContainer(nodeacls.NetworkID(network))
  39. if err != nil {
  40. logger.Log(1, "failed to remove the node acls during network delete for network,", network)
  41. }
  42. nodeCount, err := GetNetworkNonServerNodeCount(network)
  43. if nodeCount == 0 || database.IsEmptyRecord(err) {
  44. // delete server nodes first then db records
  45. if err = pro.RemoveAllNetworkUsers(network); err != nil {
  46. logger.Log(0, "failed to remove network users on network delete for network", network, err.Error())
  47. }
  48. return database.DeleteRecord(database.NETWORKS_TABLE_NAME, network)
  49. }
  50. return errors.New("node check failed. All nodes must be deleted before deleting network")
  51. }
  52. // CreateNetwork - creates a network in database
  53. func CreateNetwork(network models.Network) (models.Network, error) {
  54. if network.AddressRange != "" {
  55. normalizedRange, err := NormalizeCIDR(network.AddressRange)
  56. if err != nil {
  57. return models.Network{}, err
  58. }
  59. network.AddressRange = normalizedRange
  60. }
  61. if network.AddressRange6 != "" {
  62. normalizedRange, err := NormalizeCIDR(network.AddressRange6)
  63. if err != nil {
  64. return models.Network{}, err
  65. }
  66. network.AddressRange6 = normalizedRange
  67. }
  68. network.SetDefaults()
  69. network.SetNodesLastModified()
  70. network.SetNetworkLastModified()
  71. pro.AddProNetDefaults(&network)
  72. if len(network.ProSettings.AllowedGroups) == 0 {
  73. network.ProSettings.AllowedGroups = []string{pro.DEFAULT_ALLOWED_GROUPS}
  74. }
  75. err := ValidateNetwork(&network, false)
  76. if err != nil {
  77. //logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest"))
  78. return models.Network{}, err
  79. }
  80. if err = pro.InitializeNetworkUsers(network.NetID); err != nil {
  81. return models.Network{}, err
  82. }
  83. data, err := json.Marshal(&network)
  84. if err != nil {
  85. return models.Network{}, err
  86. }
  87. if err = database.Insert(network.NetID, string(data), database.NETWORKS_TABLE_NAME); err != nil {
  88. return models.Network{}, err
  89. }
  90. // == add all current users to network as network users ==
  91. if err = InitializeNetUsers(&network); err != nil {
  92. return network, err
  93. }
  94. return network, nil
  95. }
  96. // GetNetworkNonServerNodeCount - get number of network non server nodes
  97. func GetNetworkNonServerNodeCount(networkName string) (int, error) {
  98. nodes, err := GetNetworkNodes(networkName)
  99. return len(nodes), err
  100. }
  101. // GetParentNetwork - get parent network
  102. func GetParentNetwork(networkname string) (models.Network, error) {
  103. var network models.Network
  104. networkData, err := database.FetchRecord(database.NETWORKS_TABLE_NAME, networkname)
  105. if err != nil {
  106. return network, err
  107. }
  108. if err = json.Unmarshal([]byte(networkData), &network); err != nil {
  109. return models.Network{}, err
  110. }
  111. return network, nil
  112. }
  113. // GetParentNetwork - get parent network
  114. func GetNetworkSettings(networkname string) (models.Network, error) {
  115. var network models.Network
  116. networkData, err := database.FetchRecord(database.NETWORKS_TABLE_NAME, networkname)
  117. if err != nil {
  118. return network, err
  119. }
  120. if err = json.Unmarshal([]byte(networkData), &network); err != nil {
  121. return models.Network{}, err
  122. }
  123. return network, nil
  124. }
  125. // UniqueAddress - see if address is unique
  126. func UniqueAddress(networkName string, reverse bool) (net.IP, error) {
  127. add := net.IP{}
  128. var network models.Network
  129. network, err := GetParentNetwork(networkName)
  130. if err != nil {
  131. logger.Log(0, "UniqueAddressServer encountered an error")
  132. return add, err
  133. }
  134. if network.IsIPv4 == "no" {
  135. return add, fmt.Errorf("IPv4 not active on network " + networkName)
  136. }
  137. //ensure AddressRange is valid
  138. if _, _, err := net.ParseCIDR(network.AddressRange); err != nil {
  139. logger.Log(0, "UniqueAddress encountered an error")
  140. return add, err
  141. }
  142. net4 := iplib.Net4FromStr(network.AddressRange)
  143. newAddrs := net4.FirstAddress()
  144. if reverse {
  145. newAddrs = net4.LastAddress()
  146. }
  147. for {
  148. if IsIPUnique(networkName, newAddrs.String(), database.NODES_TABLE_NAME, false) &&
  149. IsIPUnique(networkName, newAddrs.String(), database.EXT_CLIENT_TABLE_NAME, false) {
  150. return newAddrs, nil
  151. }
  152. if reverse {
  153. newAddrs, err = net4.PreviousIP(newAddrs)
  154. } else {
  155. newAddrs, err = net4.NextIP(newAddrs)
  156. }
  157. if err != nil {
  158. break
  159. }
  160. }
  161. return add, errors.New("ERROR: No unique addresses available. Check network subnet")
  162. }
  163. // IsIPUnique - checks if an IP is unique
  164. func IsIPUnique(network string, ip string, tableName string, isIpv6 bool) bool {
  165. isunique := true
  166. if tableName == database.NODES_TABLE_NAME {
  167. nodes, err := GetNetworkNodes(network)
  168. if err != nil {
  169. return isunique
  170. }
  171. for _, node := range nodes {
  172. if isIpv6 {
  173. if node.Address6.IP.String() == ip && node.Network == network {
  174. return false
  175. }
  176. } else {
  177. if node.Address.IP.String() == ip && node.Network == network {
  178. return false
  179. }
  180. }
  181. }
  182. } else if tableName == database.EXT_CLIENT_TABLE_NAME {
  183. collection, err := database.FetchRecords(tableName)
  184. if err != nil {
  185. return isunique
  186. }
  187. var extClient models.ExtClient
  188. for _, value := range collection { // filter
  189. if err = json.Unmarshal([]byte(value), &extClient); err != nil {
  190. continue
  191. }
  192. if isIpv6 {
  193. if (extClient.Address6 == ip) && extClient.Network == network {
  194. return false
  195. }
  196. } else {
  197. if (extClient.Address == ip) && extClient.Network == network {
  198. return false
  199. }
  200. }
  201. }
  202. }
  203. return isunique
  204. }
  205. // UniqueAddress6 - see if ipv6 address is unique
  206. func UniqueAddress6(networkName string, reverse bool) (net.IP, error) {
  207. add := net.IP{}
  208. var network models.Network
  209. network, err := GetParentNetwork(networkName)
  210. if err != nil {
  211. fmt.Println("Network Not Found")
  212. return add, err
  213. }
  214. if network.IsIPv6 == "no" {
  215. return add, fmt.Errorf("IPv6 not active on network " + networkName)
  216. }
  217. //ensure AddressRange is valid
  218. if _, _, err := net.ParseCIDR(network.AddressRange6); err != nil {
  219. return add, err
  220. }
  221. net6 := iplib.Net6FromStr(network.AddressRange6)
  222. newAddrs, err := net6.NextIP(net6.FirstAddress())
  223. if reverse {
  224. newAddrs, err = net6.PreviousIP(net6.LastAddress())
  225. }
  226. if err != nil {
  227. return add, err
  228. }
  229. for {
  230. if IsIPUnique(networkName, newAddrs.String(), database.NODES_TABLE_NAME, true) &&
  231. IsIPUnique(networkName, newAddrs.String(), database.EXT_CLIENT_TABLE_NAME, true) {
  232. return newAddrs, nil
  233. }
  234. if reverse {
  235. newAddrs, err = net6.PreviousIP(newAddrs)
  236. } else {
  237. newAddrs, err = net6.NextIP(newAddrs)
  238. }
  239. if err != nil {
  240. break
  241. }
  242. }
  243. return add, errors.New("ERROR: No unique IPv6 addresses available. Check network subnet")
  244. }
  245. // IsNetworkNameUnique - checks to see if any other networks have the same name (id)
  246. func IsNetworkNameUnique(network *models.Network) (bool, error) {
  247. isunique := true
  248. dbs, err := GetNetworks()
  249. if err != nil && !database.IsEmptyRecord(err) {
  250. return false, err
  251. }
  252. for i := 0; i < len(dbs); i++ {
  253. if network.NetID == dbs[i].NetID {
  254. isunique = false
  255. }
  256. }
  257. return isunique, nil
  258. }
  259. // UpdateNetwork - updates a network with another network's fields
  260. func UpdateNetwork(currentNetwork *models.Network, newNetwork *models.Network) (bool, bool, bool, []string, []string, error) {
  261. if err := ValidateNetwork(newNetwork, true); err != nil {
  262. return false, false, false, nil, nil, err
  263. }
  264. if newNetwork.NetID == currentNetwork.NetID {
  265. hasrangeupdate4 := newNetwork.AddressRange != currentNetwork.AddressRange
  266. hasrangeupdate6 := newNetwork.AddressRange6 != currentNetwork.AddressRange6
  267. hasholepunchupdate := newNetwork.DefaultUDPHolePunch != currentNetwork.DefaultUDPHolePunch
  268. groupDelta := append(StringDifference(newNetwork.ProSettings.AllowedGroups, currentNetwork.ProSettings.AllowedGroups),
  269. StringDifference(currentNetwork.ProSettings.AllowedGroups, newNetwork.ProSettings.AllowedGroups)...)
  270. userDelta := append(StringDifference(newNetwork.ProSettings.AllowedUsers, currentNetwork.ProSettings.AllowedUsers),
  271. StringDifference(currentNetwork.ProSettings.AllowedUsers, newNetwork.ProSettings.AllowedUsers)...)
  272. data, err := json.Marshal(newNetwork)
  273. if err != nil {
  274. return false, false, false, nil, nil, err
  275. }
  276. newNetwork.SetNetworkLastModified()
  277. err = database.Insert(newNetwork.NetID, string(data), database.NETWORKS_TABLE_NAME)
  278. return hasrangeupdate4, hasrangeupdate6, hasholepunchupdate, groupDelta, userDelta, err
  279. }
  280. // copy values
  281. return false, false, false, nil, nil, errors.New("failed to update network " + newNetwork.NetID + ", cannot change netid.")
  282. }
  283. // GetNetwork - gets a network from database
  284. func GetNetwork(networkname string) (models.Network, error) {
  285. var network models.Network
  286. networkData, err := database.FetchRecord(database.NETWORKS_TABLE_NAME, networkname)
  287. if err != nil {
  288. return network, err
  289. }
  290. if err = json.Unmarshal([]byte(networkData), &network); err != nil {
  291. return models.Network{}, err
  292. }
  293. return network, nil
  294. }
  295. // NetIDInNetworkCharSet - checks if a netid of a network uses valid characters
  296. func NetIDInNetworkCharSet(network *models.Network) bool {
  297. charset := "abcdefghijklmnopqrstuvwxyz1234567890-_"
  298. for _, char := range network.NetID {
  299. if !strings.Contains(charset, string(char)) {
  300. return false
  301. }
  302. }
  303. return true
  304. }
  305. // Validate - validates fields of an network struct
  306. func ValidateNetwork(network *models.Network, isUpdate bool) error {
  307. v := validator.New()
  308. _ = v.RegisterValidation("netid_valid", func(fl validator.FieldLevel) bool {
  309. inCharSet := NetIDInNetworkCharSet(network)
  310. if isUpdate {
  311. return inCharSet
  312. }
  313. isFieldUnique, _ := IsNetworkNameUnique(network)
  314. return isFieldUnique && inCharSet
  315. })
  316. //
  317. _ = v.RegisterValidation("checkyesorno", func(fl validator.FieldLevel) bool {
  318. return validation.CheckYesOrNo(fl)
  319. })
  320. err := v.Struct(network)
  321. if err != nil {
  322. for _, e := range err.(validator.ValidationErrors) {
  323. fmt.Println(e)
  324. }
  325. }
  326. if network.ProSettings != nil {
  327. if network.ProSettings.DefaultAccessLevel < pro.NET_ADMIN || network.ProSettings.DefaultAccessLevel > pro.NO_ACCESS {
  328. return fmt.Errorf("invalid access level")
  329. }
  330. if network.ProSettings.DefaultUserClientLimit < 0 || network.ProSettings.DefaultUserNodeLimit < 0 {
  331. return fmt.Errorf("invalid node/client limit provided")
  332. }
  333. }
  334. return err
  335. }
  336. // ParseNetwork - parses a network into a model
  337. func ParseNetwork(value string) (models.Network, error) {
  338. var network models.Network
  339. err := json.Unmarshal([]byte(value), &network)
  340. return network, err
  341. }
  342. // SaveNetwork - save network struct to database
  343. func SaveNetwork(network *models.Network) error {
  344. data, err := json.Marshal(network)
  345. if err != nil {
  346. return err
  347. }
  348. if err := database.Insert(network.NetID, string(data), database.NETWORKS_TABLE_NAME); err != nil {
  349. return err
  350. }
  351. return nil
  352. }
  353. // NetworkExists - check if network exists
  354. func NetworkExists(name string) (bool, error) {
  355. var network string
  356. var err error
  357. if network, err = database.FetchRecord(database.NETWORKS_TABLE_NAME, name); err != nil {
  358. return false, err
  359. }
  360. return len(network) > 0, nil
  361. }
  362. // SortNetworks - Sorts slice of Networks by their NetID alphabetically with numbers first
  363. func SortNetworks(unsortedNetworks []models.Network) {
  364. sort.Slice(unsortedNetworks, func(i, j int) bool {
  365. return unsortedNetworks[i].NetID < unsortedNetworks[j].NetID
  366. })
  367. }
  368. // == Private ==