helpers.go 17 KB

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