helpers.go 14 KB

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