helpers.go 17 KB

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