util.go 4.3 KB

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