helpers.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  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. "net"
  13. "github.com/gravitl/netmaker/models"
  14. "github.com/gravitl/netmaker/mongoconn"
  15. "go.mongodb.org/mongo-driver/bson"
  16. "go.mongodb.org/mongo-driver/bson/primitive"
  17. "go.mongodb.org/mongo-driver/mongo/options"
  18. "go.mongodb.org/mongo-driver/mongo"
  19. )
  20. //Takes in an arbitrary field and value for field and checks to see if any other
  21. //node has that value for the same field within the network
  22. func CreateServerToken(netID string) (string, error) {
  23. var network models.Network
  24. var accesskey models.AccessKey
  25. network, err := GetParentNetwork(netID)
  26. if err != nil {
  27. return "", err
  28. }
  29. accesskey.Name = GenKeyName()
  30. accesskey.Value = GenKey()
  31. accesskey.Uses = 1
  32. _, gconf, errG := GetGlobalConfig()
  33. if errG != nil {
  34. return "", errG
  35. }
  36. address := "localhost" + gconf.PortGRPC
  37. accessstringdec := address + "." + netID + "." + accesskey.Value
  38. accesskey.AccessString = base64.StdEncoding.EncodeToString([]byte(accessstringdec))
  39. network.AccessKeys = append(network.AccessKeys, accesskey)
  40. collection := mongoconn.Client.Database("netmaker").Collection("networks")
  41. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  42. // Create filter
  43. filter := bson.M{"netid": netID}
  44. // Read update model from body request
  45. fmt.Println("Adding key to " + network.NetID)
  46. // prepare update model.
  47. update := bson.D{
  48. {"$set", bson.D{
  49. {"accesskeys", network.AccessKeys},
  50. }},
  51. }
  52. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
  53. defer cancel()
  54. if errN != nil {
  55. return "", errN
  56. }
  57. return accesskey.AccessString, nil
  58. }
  59. func IsFieldUnique(network string, field string, value string) bool {
  60. var node models.Node
  61. isunique := true
  62. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  63. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  64. filter := bson.M{field: value, "network": network}
  65. err := collection.FindOne(ctx, filter).Decode(&node)
  66. defer cancel()
  67. if err != nil {
  68. return isunique
  69. }
  70. if (node.Name != "") {
  71. isunique = false
  72. }
  73. return isunique
  74. }
  75. func NetworkExists(name string) (bool, error) {
  76. collection := mongoconn.Client.Database("netmaker").Collection("networks")
  77. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  78. filter := bson.M{"netid": name}
  79. var result bson.M
  80. err := collection.FindOne(ctx, filter).Decode(&result)
  81. defer cancel()
  82. if err != nil {
  83. if err == mongo.ErrNoDocuments {
  84. return false, nil
  85. }
  86. fmt.Println("ERROR RETRIEVING GROUP!")
  87. fmt.Println(err)
  88. }
  89. return true, err
  90. }
  91. //TODO: This is very inefficient (N-squared). Need to find a better way.
  92. //Takes a list of nodes in a network and iterates through
  93. //for each node, it gets a unique address. That requires checking against all other nodes once more
  94. func UpdateNetworkNodeAddresses(networkName string) error {
  95. //Connection mongoDB with mongoconn class
  96. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  97. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  98. filter := bson.M{"network": networkName}
  99. cur, err := collection.Find(ctx, filter)
  100. if err != nil {
  101. return err
  102. }
  103. defer cancel()
  104. for cur.Next(context.TODO()) {
  105. var node models.Node
  106. err := cur.Decode(&node)
  107. if err != nil {
  108. fmt.Println("error in node address assignment!")
  109. return err
  110. }
  111. ipaddr, iperr := UniqueAddress(networkName)
  112. if iperr != nil {
  113. fmt.Println("error in node address assignment!")
  114. return iperr
  115. }
  116. filter := bson.M{"macaddress": node.MacAddress}
  117. update := bson.D{{"$set", bson.D{{"address", ipaddr}}}}
  118. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&node)
  119. defer cancel()
  120. if errN != nil {
  121. return errN
  122. }
  123. }
  124. return err
  125. }
  126. //TODO TODO TODO!!!!!
  127. func UpdateNetworkPrivateAddresses(networkName string) error {
  128. //Connection mongoDB with mongoconn class
  129. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  130. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  131. filter := bson.M{"network": networkName}
  132. cur, err := collection.Find(ctx, filter)
  133. if err != nil {
  134. return err
  135. }
  136. defer cancel()
  137. for cur.Next(context.TODO()) {
  138. var node models.Node
  139. err := cur.Decode(&node)
  140. if err != nil {
  141. fmt.Println("error in node address assignment!")
  142. return err
  143. }
  144. ipaddr, iperr := UniqueAddress(networkName)
  145. if iperr != nil {
  146. fmt.Println("error in node address assignment!")
  147. return iperr
  148. }
  149. filter := bson.M{"macaddress": node.MacAddress}
  150. update := bson.D{{"$set", bson.D{{"address", ipaddr}}}}
  151. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&node)
  152. defer cancel()
  153. if errN != nil {
  154. return errN
  155. }
  156. }
  157. return err
  158. }
  159. //Checks to see if any other networks have the same name (id)
  160. func IsNetworkNameUnique(name string) (bool, error ){
  161. isunique := true
  162. dbs, err := ListNetworks()
  163. if err != nil {
  164. return false, err
  165. }
  166. for i := 0; i < len(dbs); i++ {
  167. if name == dbs[i].NetID {
  168. isunique = false
  169. }
  170. }
  171. return isunique, nil
  172. }
  173. func IsNetworkDisplayNameUnique(name string) (bool, error){
  174. isunique := true
  175. dbs, err := ListNetworks()
  176. if err != nil {
  177. return false, err
  178. }
  179. for i := 0; i < len(dbs); i++ {
  180. if name == dbs[i].DisplayName {
  181. isunique = false
  182. }
  183. }
  184. return isunique, nil
  185. }
  186. func GetNetworkNodeNumber(networkName string) (int, error){
  187. collection := mongoconn.Client.Database("wirecat").Collection("nodes")
  188. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  189. filter := bson.M{"network": networkName}
  190. count, err := collection.CountDocuments(ctx, filter)
  191. returncount := int(count)
  192. //not sure if this is the right way of handling this error...
  193. if err != nil {
  194. return 9999, err
  195. }
  196. defer cancel()
  197. return returncount, err
  198. }
  199. //Kind of a weird name. Should just be GetNetworks I think. Consider changing.
  200. //Anyway, returns all the networks
  201. func ListNetworks() ([]models.Network, error){
  202. var networks []models.Network
  203. collection := mongoconn.Client.Database("netmaker").Collection("networks")
  204. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  205. cur, err := collection.Find(ctx, bson.M{}, options.Find().SetProjection(bson.M{"_id": 0}))
  206. if err != nil {
  207. return networks, err
  208. }
  209. defer cancel()
  210. for cur.Next(context.TODO()) {
  211. var network models.Network
  212. err := cur.Decode(&network)
  213. if err != nil {
  214. return networks, err
  215. }
  216. // add network our array
  217. networks = append(networks, network)
  218. }
  219. if err := cur.Err(); err != nil {
  220. return networks, err
  221. }
  222. return networks, err
  223. }
  224. //Checks to see if access key is valid
  225. //Does so by checking against all keys and seeing if any have the same value
  226. //may want to hash values before comparing...consider this
  227. //TODO: No error handling!!!!
  228. func IsKeyValid(networkname string, keyvalue string) bool{
  229. network, _ := GetParentNetwork(networkname)
  230. var key models.AccessKey
  231. foundkey := false
  232. isvalid := false
  233. for i := len(network.AccessKeys) - 1; i >= 0; i-- {
  234. currentkey:= network.AccessKeys[i]
  235. if currentkey.Value == keyvalue {
  236. key = currentkey
  237. foundkey = true
  238. }
  239. }
  240. if foundkey {
  241. if key.Uses > 0 {
  242. isvalid = true
  243. }
  244. }
  245. return isvalid
  246. }
  247. //TODO: Contains a fatal error return. Need to change
  248. //This just gets a network object from a network name
  249. //Should probably just be GetNetwork. kind of a dumb name.
  250. //Used in contexts where it's not the Parent network.
  251. func GetParentNetwork(networkname string) (models.Network, error) {
  252. var network models.Network
  253. collection := mongoconn.Client.Database("netmaker").Collection("networks")
  254. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  255. filter := bson.M{"netid": networkname}
  256. err := collection.FindOne(ctx, filter).Decode(&network)
  257. defer cancel()
  258. if err != nil {
  259. return network, err
  260. }
  261. return network, nil
  262. }
  263. //Check for valid IPv4 address
  264. //Note: We dont handle IPv6 AT ALL!!!!! This definitely is needed at some point
  265. //But for iteration 1, lets just stick to IPv4. Keep it simple stupid.
  266. func IsIpv4Net(host string) bool {
  267. return net.ParseIP(host) != nil
  268. }
  269. //Similar to above but checks if Cidr range is valid
  270. //At least this guy's got some print statements
  271. //still not good error handling
  272. func IsIpv4CIDR(host string) bool {
  273. ip, ipnet, err := net.ParseCIDR(host)
  274. if err != nil {
  275. fmt.Println(err)
  276. fmt.Println("Address Range is not valid!")
  277. return false
  278. }
  279. return ip != nil && ipnet != nil
  280. }
  281. //This is used to validate public keys (make sure they're base64 encoded like all public keys should be).
  282. func IsBase64(s string) bool {
  283. _, err := base64.StdEncoding.DecodeString(s)
  284. return err == nil
  285. }
  286. //This should probably just be called GetNode
  287. //It returns a node based on the ID of the node.
  288. //Why do we need this?
  289. //TODO: Check references. This seems unnecessary.
  290. func GetNodeObj(id primitive.ObjectID) models.Node {
  291. var node models.Node
  292. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  293. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  294. filter := bson.M{"_id": id}
  295. err := collection.FindOne(ctx, filter).Decode(&node)
  296. defer cancel()
  297. if err != nil {
  298. fmt.Println(err)
  299. fmt.Println("Did not get the node...")
  300. return node
  301. }
  302. fmt.Println("Got node " + node.Name)
  303. return node
  304. }
  305. //This checks to make sure a network name is valid.
  306. //Switch to REGEX?
  307. func NameInNetworkCharSet(name string) bool{
  308. charset := "abcdefghijklmnopqrstuvwxyz1234567890-_"
  309. for _, char := range name {
  310. if !strings.Contains(charset, strings.ToLower(string(char))) {
  311. return false
  312. }
  313. }
  314. return true
  315. }
  316. func NameInNodeCharSet(name string) bool{
  317. charset := "abcdefghijklmnopqrstuvwxyz1234567890-"
  318. for _, char := range name {
  319. if !strings.Contains(charset, strings.ToLower(string(char))) {
  320. return false
  321. }
  322. }
  323. return true
  324. }
  325. //This returns a node based on its mac address.
  326. //The mac address acts as the Unique ID for nodes.
  327. //Is this a dumb thing to do? I thought it was cool but maybe it's dumb.
  328. //It doesn't really provide a tangible benefit over a random ID
  329. func GetNodeByMacAddress(network string, macaddress string) (models.Node, error) {
  330. var node models.Node
  331. filter := bson.M{"macaddress": macaddress, "network": network}
  332. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  333. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  334. err := collection.FindOne(ctx, filter).Decode(&node)
  335. defer cancel()
  336. if err != nil {
  337. return node, err
  338. }
  339. return node, nil
  340. }
  341. //This returns a unique address for a node to use
  342. //it iterates through the list of IP's in the subnet
  343. //and checks against all nodes to see if it's taken, until it finds one.
  344. //TODO: We do not handle a case where we run out of addresses.
  345. //We will need to handle that eventually
  346. func UniqueAddress(networkName string) (string, error){
  347. var network models.Network
  348. network, err := GetParentNetwork(networkName)
  349. if err != nil {
  350. fmt.Println("UniqueAddress encountered an error")
  351. return "666", err
  352. }
  353. offset := true
  354. ip, ipnet, err := net.ParseCIDR(network.AddressRange)
  355. if err != nil {
  356. fmt.Println("UniqueAddress encountered an error")
  357. return "666", err
  358. }
  359. for ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); Inc(ip) {
  360. if offset {
  361. offset = false
  362. continue
  363. }
  364. if IsIPUnique(networkName, ip.String()){
  365. return ip.String(), err
  366. }
  367. }
  368. //TODO
  369. err1 := errors.New("ERROR: No unique addresses available. Check network subnet.")
  370. return "W1R3: NO UNIQUE ADDRESSES AVAILABLE", err1
  371. }
  372. //pretty simple get
  373. func GetGlobalConfig() (bool, models.GlobalConfig, error) {
  374. create := false
  375. filter := bson.M{}
  376. var globalconf models.GlobalConfig
  377. collection := mongoconn.Client.Database("netmaker").Collection("config")
  378. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  379. err := collection.FindOne(ctx, filter).Decode(&globalconf)
  380. defer cancel()
  381. if err == mongo.ErrNoDocuments {
  382. fmt.Println("Global config does not exist. Need to create.")
  383. create = true
  384. return create, globalconf, err
  385. } else if err != nil {
  386. fmt.Println(err)
  387. fmt.Println("Could not get global config")
  388. return create, globalconf, err
  389. }
  390. return create, globalconf, err
  391. }
  392. //generate an access key value
  393. func GenKey() string {
  394. var seededRand *rand.Rand = rand.New(
  395. rand.NewSource(time.Now().UnixNano()))
  396. length := 16
  397. charset := "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  398. b := make([]byte, length)
  399. for i := range b {
  400. b[i] = charset[seededRand.Intn(len(charset))]
  401. }
  402. return string(b)
  403. }
  404. //generate a key value
  405. //we should probably just have 1 random string generator
  406. //that can be used across all functions
  407. //have a "base string" a "length" and a "charset"
  408. func GenKeyName() string {
  409. var seededRand *rand.Rand = rand.New(
  410. rand.NewSource(time.Now().UnixNano()))
  411. length := 5
  412. charset := "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  413. b := make([]byte, length)
  414. for i := range b {
  415. b[i] = charset[seededRand.Intn(len(charset))]
  416. }
  417. return "key-" + string(b)
  418. }
  419. //checks if IP is unique in the address range
  420. //used by UniqueAddress
  421. func IsIPUnique(network string, ip string) bool {
  422. var node models.Node
  423. isunique := true
  424. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  425. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  426. filter := bson.M{"address": ip, "network": network}
  427. err := collection.FindOne(ctx, filter).Decode(&node)
  428. defer cancel()
  429. if err != nil {
  430. fmt.Println(err)
  431. return isunique
  432. }
  433. if (node.Address == ip) {
  434. isunique = false
  435. }
  436. return isunique
  437. }
  438. //called once key has been used by createNode
  439. //reduces value by one and deletes if necessary
  440. func DecrimentKey(networkName string, keyvalue string) {
  441. var network models.Network
  442. network, err := GetParentNetwork(networkName)
  443. if err != nil {
  444. return
  445. }
  446. for i := len(network.AccessKeys) - 1; i >= 0; i-- {
  447. currentkey := network.AccessKeys[i]
  448. if currentkey.Value == keyvalue {
  449. network.AccessKeys[i].Uses--
  450. if network.AccessKeys[i].Uses < 1 {
  451. //this is the part where it will call the delete
  452. //not sure if there's edge cases I'm missing
  453. DeleteKey(network, i)
  454. return
  455. }
  456. }
  457. }
  458. collection := mongoconn.Client.Database("netmaker").Collection("networks")
  459. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  460. filter := bson.M{"netid": network.NetID}
  461. update := bson.D{
  462. {"$set", bson.D{
  463. {"accesskeys", network.AccessKeys},
  464. }},
  465. }
  466. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
  467. defer cancel()
  468. if errN != nil {
  469. return
  470. }
  471. }
  472. //takes the logic from controllers.deleteKey
  473. func DeleteKey(network models.Network, i int) {
  474. network.AccessKeys = append(network.AccessKeys[:i],
  475. network.AccessKeys[i+1:]...)
  476. collection := mongoconn.Client.Database("netmaker").Collection("networks")
  477. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  478. // Create filter
  479. filter := bson.M{"netid": network.NetID}
  480. // prepare update model.
  481. update := bson.D{
  482. {"$set", bson.D{
  483. {"accesskeys", network.AccessKeys},
  484. }},
  485. }
  486. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
  487. defer cancel()
  488. if errN != nil {
  489. return
  490. }
  491. }
  492. //increments an IP over the previous
  493. func Inc(ip net.IP) {
  494. for j := len(ip)-1; j>=0; j-- {
  495. ip[j]++
  496. if ip[j] > 0 {
  497. break
  498. }
  499. }
  500. }