helpers.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. //TODO: Consider restructuring this file/folder "github.com/gorilla/handlers"
  2. //It may make more sense to split into different files and not call it "helpers"
  3. package functions
  4. import (
  5. "fmt"
  6. "errors"
  7. "math/rand"
  8. "time"
  9. "context"
  10. "encoding/base64"
  11. "strings"
  12. "log"
  13. "net"
  14. "github.com/gravitl/netmaker/models"
  15. "github.com/gravitl/netmaker/mongoconn"
  16. "go.mongodb.org/mongo-driver/bson"
  17. "go.mongodb.org/mongo-driver/bson/primitive"
  18. "go.mongodb.org/mongo-driver/mongo/options"
  19. "go.mongodb.org/mongo-driver/mongo"
  20. )
  21. //Takes in an arbitrary field and value for field and checks to see if any other
  22. //node has that value for the same field within the group
  23. func IsFieldUnique(group string, field string, value string) bool {
  24. var node models.Node
  25. isunique := true
  26. collection := mongoconn.Client.Database("wirecat").Collection("nodes")
  27. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  28. filter := bson.M{field: value, "group": group}
  29. err := collection.FindOne(ctx, filter).Decode(&node)
  30. defer cancel()
  31. if err != nil {
  32. return isunique
  33. }
  34. if (node.Name != "") {
  35. isunique = false
  36. }
  37. return isunique
  38. }
  39. func GroupExists(name string) (bool, error) {
  40. collection := mongoconn.Client.Database("wirecat").Collection("groups")
  41. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  42. filter := bson.M{"nameid": name}
  43. var result bson.M
  44. err := collection.FindOne(ctx, filter).Decode(&result)
  45. defer cancel()
  46. if err != nil {
  47. if err == mongo.ErrNoDocuments {
  48. return false, err
  49. }
  50. log.Fatal(err)
  51. }
  52. return true, err
  53. }
  54. //TODO: This is very inefficient (N-squared). Need to find a better way.
  55. //Takes a list of nodes in a group and iterates through
  56. //for each node, it gets a unique address. That requires checking against all other nodes once more
  57. func UpdateGroupNodeAddresses(groupName string) error {
  58. //Connection mongoDB with mongoconn class
  59. collection := mongoconn.Client.Database("wirecat").Collection("nodes")
  60. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  61. filter := bson.M{"group": groupName}
  62. cur, err := collection.Find(ctx, filter)
  63. if err != nil {
  64. return err
  65. }
  66. defer cancel()
  67. for cur.Next(context.TODO()) {
  68. var node models.Node
  69. err := cur.Decode(&node)
  70. if err != nil {
  71. fmt.Println("error in node address assignment!")
  72. return err
  73. }
  74. ipaddr, iperr := UniqueAddress(groupName)
  75. if iperr != nil {
  76. fmt.Println("error in node address assignment!")
  77. return iperr
  78. }
  79. filter := bson.M{"macaddress": node.MacAddress}
  80. update := bson.D{{"$set", bson.D{{"address", ipaddr}}}}
  81. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&node)
  82. defer cancel()
  83. if errN != nil {
  84. return errN
  85. }
  86. }
  87. return err
  88. }
  89. //Checks to see if any other groups have the same name (id)
  90. func IsGroupNameUnique(name string) bool {
  91. isunique := true
  92. dbs := ListGroups()
  93. for i := 0; i < len(dbs); i++ {
  94. if name == dbs[i].NameID {
  95. isunique = false
  96. }
  97. }
  98. return isunique
  99. }
  100. func IsGroupDisplayNameUnique(name string) bool {
  101. isunique := true
  102. dbs := ListGroups()
  103. for i := 0; i < len(dbs); i++ {
  104. if name == dbs[i].DisplayName {
  105. isunique = false
  106. }
  107. }
  108. return isunique
  109. }
  110. //Kind of a weird name. Should just be GetGroups I think. Consider changing.
  111. //Anyway, returns all the groups
  112. func ListGroups() []models.Group{
  113. var groups []models.Group
  114. collection := mongoconn.Client.Database("wirecat").Collection("groups")
  115. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  116. cur, err := collection.Find(ctx, bson.M{}, options.Find().SetProjection(bson.M{"_id": 0}))
  117. if err != nil {
  118. return groups
  119. }
  120. defer cancel()
  121. for cur.Next(context.TODO()) {
  122. var group models.Group
  123. err := cur.Decode(&group)
  124. if err != nil {
  125. log.Fatal(err)
  126. }
  127. // add group our array
  128. groups = append(groups, group)
  129. }
  130. if err := cur.Err(); err != nil {
  131. log.Fatal(err)
  132. }
  133. return groups
  134. }
  135. //Checks to see if access key is valid
  136. //Does so by checking against all keys and seeing if any have the same value
  137. //may want to hash values before comparing...consider this
  138. //TODO: No error handling!!!!
  139. func IsKeyValid(groupname string, keyvalue string) bool{
  140. group, _ := GetParentGroup(groupname)
  141. var key models.AccessKey
  142. foundkey := false
  143. isvalid := false
  144. for i := len(group.AccessKeys) - 1; i >= 0; i-- {
  145. currentkey:= group.AccessKeys[i]
  146. if currentkey.Value == keyvalue {
  147. key = currentkey
  148. foundkey = true
  149. }
  150. }
  151. if foundkey {
  152. if key.Uses > 0 {
  153. isvalid = true
  154. }
  155. }
  156. return isvalid
  157. }
  158. //TODO: Contains a fatal error return. Need to change
  159. //This just gets a group object from a group name
  160. //Should probably just be GetGroup. kind of a dumb name.
  161. //Used in contexts where it's not the Parent group.
  162. func GetParentGroup(groupname string) (models.Group, error) {
  163. var group models.Group
  164. collection := mongoconn.Client.Database("wirecat").Collection("groups")
  165. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  166. filter := bson.M{"nameid": groupname}
  167. err := collection.FindOne(ctx, filter).Decode(&group)
  168. defer cancel()
  169. if err != nil {
  170. return group, err
  171. }
  172. return group, nil
  173. }
  174. //Check for valid IPv4 address
  175. //Note: We dont handle IPv6 AT ALL!!!!! This definitely is needed at some point
  176. //But for iteration 1, lets just stick to IPv4. Keep it simple stupid.
  177. func IsIpv4Net(host string) bool {
  178. return net.ParseIP(host) != nil
  179. }
  180. //Similar to above but checks if Cidr range is valid
  181. //At least this guy's got some print statements
  182. //still not good error handling
  183. func IsIpv4CIDR(host string) bool {
  184. ip, ipnet, err := net.ParseCIDR(host)
  185. if err != nil {
  186. fmt.Println(err)
  187. fmt.Println("Address Range is not valid!")
  188. return false
  189. }
  190. return ip != nil && ipnet != nil
  191. }
  192. //This is used to validate public keys (make sure they're base64 encoded like all public keys should be).
  193. func IsBase64(s string) bool {
  194. _, err := base64.StdEncoding.DecodeString(s)
  195. return err == nil
  196. }
  197. //This should probably just be called GetNode
  198. //It returns a node based on the ID of the node.
  199. //Why do we need this?
  200. //TODO: Check references. This seems unnecessary.
  201. func GetNodeObj(id primitive.ObjectID) models.Node {
  202. var node models.Node
  203. collection := mongoconn.Client.Database("wirecat").Collection("nodes")
  204. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  205. filter := bson.M{"_id": id}
  206. err := collection.FindOne(ctx, filter).Decode(&node)
  207. defer cancel()
  208. if err != nil {
  209. fmt.Println(err)
  210. fmt.Println("Did not get the node...")
  211. return node
  212. }
  213. fmt.Println("Got node " + node.Name)
  214. return node
  215. }
  216. //This checks to make sure a group name is valid.
  217. //Switch to REGEX?
  218. func NameInGroupCharSet(name string) bool{
  219. charset := "abcdefghijklmnopqrstuvwxyz1234567890-_"
  220. for _, char := range name {
  221. if !strings.Contains(charset, strings.ToLower(string(char))) {
  222. return false
  223. }
  224. }
  225. return true
  226. }
  227. func NameInNodeCharSet(name string) bool{
  228. charset := "abcdefghijklmnopqrstuvwxyz1234567890-"
  229. for _, char := range name {
  230. if !strings.Contains(charset, strings.ToLower(string(char))) {
  231. return false
  232. }
  233. }
  234. return true
  235. }
  236. //This returns a node based on its mac address.
  237. //The mac address acts as the Unique ID for nodes.
  238. //Is this a dumb thing to do? I thought it was cool but maybe it's dumb.
  239. //It doesn't really provide a tangible benefit over a random ID
  240. func GetNodeByMacAddress(group string, macaddress string) (models.Node, error) {
  241. var node models.Node
  242. filter := bson.M{"macaddress": macaddress, "group": group}
  243. collection := mongoconn.Client.Database("wirecat").Collection("nodes")
  244. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  245. err := collection.FindOne(ctx, filter).Decode(&node)
  246. defer cancel()
  247. if err != nil {
  248. return node, err
  249. }
  250. return node, nil
  251. }
  252. //This returns a unique address for a node to use
  253. //it iterates through the list of IP's in the subnet
  254. //and checks against all nodes to see if it's taken, until it finds one.
  255. //TODO: We do not handle a case where we run out of addresses.
  256. //We will need to handle that eventually
  257. func UniqueAddress(groupName string) (string, error){
  258. var group models.Group
  259. group, err := GetParentGroup(groupName)
  260. if err != nil {
  261. fmt.Println("UniqueAddress encountered an error")
  262. return "666", err
  263. }
  264. offset := true
  265. ip, ipnet, err := net.ParseCIDR(group.AddressRange)
  266. if err != nil {
  267. fmt.Println("UniqueAddress encountered an error")
  268. return "666", err
  269. }
  270. for ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); Inc(ip) {
  271. if offset {
  272. offset = false
  273. continue
  274. }
  275. if IsIPUnique(groupName, ip.String()){
  276. return ip.String(), err
  277. }
  278. }
  279. //TODO
  280. err1 := errors.New("ERROR: No unique addresses available. Check group subnet.")
  281. return "W1R3: NO UNIQUE ADDRESSES AVAILABLE", err1
  282. }
  283. //generate an access key value
  284. func GenKey() string {
  285. var seededRand *rand.Rand = rand.New(
  286. rand.NewSource(time.Now().UnixNano()))
  287. length := 16
  288. charset := "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  289. b := make([]byte, length)
  290. for i := range b {
  291. b[i] = charset[seededRand.Intn(len(charset))]
  292. }
  293. return string(b)
  294. }
  295. //generate a key value
  296. //we should probably just have 1 random string generator
  297. //that can be used across all functions
  298. //have a "base string" a "length" and a "charset"
  299. func GenKeyName() string {
  300. var seededRand *rand.Rand = rand.New(
  301. rand.NewSource(time.Now().UnixNano()))
  302. length := 5
  303. charset := "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  304. b := make([]byte, length)
  305. for i := range b {
  306. b[i] = charset[seededRand.Intn(len(charset))]
  307. }
  308. return "key-" + string(b)
  309. }
  310. //checks if IP is unique in the address range
  311. //used by UniqueAddress
  312. func IsIPUnique(group string, ip string) bool {
  313. var node models.Node
  314. isunique := true
  315. collection := mongoconn.Client.Database("wirecat").Collection("nodes")
  316. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  317. filter := bson.M{"address": ip, "group": group}
  318. err := collection.FindOne(ctx, filter).Decode(&node)
  319. defer cancel()
  320. if err != nil {
  321. fmt.Println(err)
  322. return isunique
  323. }
  324. if (node.Address == ip) {
  325. isunique = false
  326. }
  327. return isunique
  328. }
  329. //called once key has been used by createNode
  330. //reduces value by one and deletes if necessary
  331. func DecrimentKey(groupName string, keyvalue string) {
  332. var group models.Group
  333. group, err := GetParentGroup(groupName)
  334. if err != nil {
  335. return
  336. }
  337. for i := len(group.AccessKeys) - 1; i >= 0; i-- {
  338. currentkey := group.AccessKeys[i]
  339. if currentkey.Value == keyvalue {
  340. group.AccessKeys[i].Uses--
  341. if group.AccessKeys[i].Uses < 1 {
  342. //this is the part where it will call the delete
  343. //not sure if there's edge cases I'm missing
  344. DeleteKey(group, i)
  345. return
  346. }
  347. }
  348. }
  349. collection := mongoconn.Client.Database("wirecat").Collection("groups")
  350. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  351. filter := bson.M{"nameid": group.NameID}
  352. update := bson.D{
  353. {"$set", bson.D{
  354. {"accesskeys", group.AccessKeys},
  355. }},
  356. }
  357. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&group)
  358. defer cancel()
  359. if errN != nil {
  360. return
  361. }
  362. }
  363. //takes the logic from controllers.deleteKey
  364. func DeleteKey(group models.Group, i int) {
  365. group.AccessKeys = append(group.AccessKeys[:i],
  366. group.AccessKeys[i+1:]...)
  367. collection := mongoconn.Client.Database("wirecat").Collection("groups")
  368. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  369. // Create filter
  370. filter := bson.M{"nameid": group.NameID}
  371. // prepare update model.
  372. update := bson.D{
  373. {"$set", bson.D{
  374. {"accesskeys", group.AccessKeys},
  375. }},
  376. }
  377. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&group)
  378. defer cancel()
  379. if errN != nil {
  380. return
  381. }
  382. }
  383. //increments an IP over the previous
  384. func Inc(ip net.IP) {
  385. for j := len(ip)-1; j>=0; j-- {
  386. ip[j]++
  387. if ip[j] > 0 {
  388. break
  389. }
  390. }
  391. }