util.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. // package for logicing client and server code
  2. package logic
  3. import (
  4. crand "crypto/rand"
  5. "encoding/base64"
  6. "encoding/json"
  7. "math/big"
  8. "math/rand"
  9. "net"
  10. "os"
  11. "strings"
  12. "time"
  13. "github.com/c-robinson/iplib"
  14. "github.com/gravitl/netmaker/database"
  15. )
  16. // IsBase64 - checks if a string is in base64 format
  17. // This is used to validate public keys (make sure they're base64 encoded like all public keys should be).
  18. func IsBase64(s string) bool {
  19. _, err := base64.StdEncoding.DecodeString(s)
  20. return err == nil
  21. }
  22. // CheckEndpoint - checks if an endpoint is valid
  23. func CheckEndpoint(endpoint string) bool {
  24. endpointarr := strings.Split(endpoint, ":")
  25. return len(endpointarr) == 2
  26. }
  27. // FileExists - checks if local file exists
  28. func FileExists(f string) bool {
  29. info, err := os.Stat(f)
  30. if os.IsNotExist(err) {
  31. return false
  32. }
  33. return !info.IsDir()
  34. }
  35. // IsAddressInCIDR - util to see if an address is in a cidr or not
  36. func IsAddressInCIDR(address net.IP, cidr string) bool {
  37. var _, currentCIDR, cidrErr = net.ParseCIDR(cidr)
  38. if cidrErr != nil {
  39. return false
  40. }
  41. return currentCIDR.Contains(address)
  42. }
  43. // SetNetworkNodesLastModified - sets the network nodes last modified
  44. func SetNetworkNodesLastModified(networkName string) error {
  45. timestamp := time.Now().Unix()
  46. network, err := GetParentNetwork(networkName)
  47. if err != nil {
  48. return err
  49. }
  50. network.NodesLastModified = timestamp
  51. data, err := json.Marshal(&network)
  52. if err != nil {
  53. return err
  54. }
  55. err = database.Insert(networkName, string(data), database.NETWORKS_TABLE_NAME)
  56. if err != nil {
  57. return err
  58. }
  59. return nil
  60. }
  61. // GenerateCryptoString - generates random string of n length
  62. func GenerateCryptoString(n int) (string, error) {
  63. const chars = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-"
  64. ret := make([]byte, n)
  65. for i := range ret {
  66. num, err := crand.Int(crand.Reader, big.NewInt(int64(len(chars))))
  67. if err != nil {
  68. return "", err
  69. }
  70. ret[i] = chars[num.Int64()]
  71. }
  72. return string(ret), nil
  73. }
  74. // RandomString - returns a random string in a charset
  75. func RandomString(length int) string {
  76. const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  77. var seededRand *rand.Rand = rand.New(rand.NewSource(time.Now().UnixNano()))
  78. b := make([]byte, length)
  79. for i := range b {
  80. b[i] = charset[seededRand.Intn(len(charset))]
  81. }
  82. return string(b)
  83. }
  84. // StringSliceContains - sees if a string slice contains a string element
  85. func StringSliceContains(slice []string, item string) bool {
  86. for _, s := range slice {
  87. if s == item {
  88. return true
  89. }
  90. }
  91. return false
  92. }
  93. // NormalCIDR - returns the first address of CIDR
  94. func NormalizeCIDR(address string) (string, error) {
  95. ip, IPNet, err := net.ParseCIDR(address)
  96. if err != nil {
  97. return "", err
  98. }
  99. if ip.To4() == nil {
  100. net6 := iplib.Net6FromStr(IPNet.String())
  101. IPNet.IP = net6.FirstAddress()
  102. } else {
  103. net4 := iplib.Net4FromStr(IPNet.String())
  104. IPNet.IP = net4.NetworkAddress()
  105. }
  106. return IPNet.String(), nil
  107. }
  108. // StringDifference - returns the elements in `a` that aren't in `b`.
  109. func StringDifference(a, b []string) []string {
  110. mb := make(map[string]struct{}, len(b))
  111. for _, x := range b {
  112. mb[x] = struct{}{}
  113. }
  114. var diff []string
  115. for _, x := range a {
  116. if _, found := mb[x]; !found {
  117. diff = append(diff, x)
  118. }
  119. }
  120. return diff
  121. }
  122. // CheckIfFileExists - checks if file exists or not in the given path
  123. func CheckIfFileExists(filePath string) bool {
  124. if _, err := os.Stat(filePath); os.IsNotExist(err) {
  125. return false
  126. }
  127. return true
  128. }
  129. // RemoveStringSlice - removes an element at given index i
  130. // from a given string slice
  131. func RemoveStringSlice(slice []string, i int) []string {
  132. return append(slice[:i], slice[i+1:]...)
  133. }
  134. // == private ==