node.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. package models
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "log"
  6. "math/rand"
  7. "net"
  8. "strings"
  9. "time"
  10. "github.com/go-playground/validator/v10"
  11. "github.com/gravitl/netmaker/database"
  12. "golang.org/x/crypto/bcrypt"
  13. )
  14. const charset = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  15. const TEN_YEARS_IN_SECONDS = 300000000
  16. var seededRand *rand.Rand = rand.New(
  17. rand.NewSource(time.Now().UnixNano()))
  18. //node struct
  19. type Node struct {
  20. ID string `json:"id,omitempty" bson:"id,omitempty"`
  21. Address string `json:"address" bson:"address" validate:"omitempty,ipv4"`
  22. Address6 string `json:"address6" bson:"address6" validate:"omitempty,ipv6"`
  23. LocalAddress string `json:"localaddress" bson:"localaddress" validate:"omitempty,ip"`
  24. Name string `json:"name" bson:"name" validate:"omitempty,max=12,in_charset"`
  25. ListenPort int32 `json:"listenport" bson:"listenport" validate:"omitempty,numeric,min=1024,max=65535"`
  26. PublicKey string `json:"publickey" bson:"publickey" validate:"required,base64"`
  27. Endpoint string `json:"endpoint" bson:"endpoint" validate:"required,ip"`
  28. PostUp string `json:"postup" bson:"postup"`
  29. PostDown string `json:"postdown" bson:"postdown"`
  30. AllowedIPs []string `json:"allowedips" bson:"allowedips"`
  31. PersistentKeepalive int32 `json:"persistentkeepalive" bson:"persistentkeepalive" validate:"omitempty,numeric,max=1000"`
  32. SaveConfig string `json:"saveconfig" bson:"saveconfig" validate:"checkyesorno"`
  33. AccessKey string `json:"accesskey" bson:"accesskey"`
  34. Interface string `json:"interface" bson:"interface"`
  35. LastModified int64 `json:"lastmodified" bson:"lastmodified"`
  36. KeyUpdateTimeStamp int64 `json:"keyupdatetimestamp" bson:"keyupdatetimestamp"`
  37. ExpirationDateTime int64 `json:"expdatetime" bson:"expdatetime"`
  38. LastPeerUpdate int64 `json:"lastpeerupdate" bson:"lastpeerupdate"`
  39. LastCheckIn int64 `json:"lastcheckin" bson:"lastcheckin"`
  40. MacAddress string `json:"macaddress" bson:"macaddress" validate:"required,mac,macaddress_unique"`
  41. CheckInInterval int32 `json:"checkininterval" bson:"checkininterval"`
  42. Password string `json:"password" bson:"password" validate:"required,min=6"`
  43. Network string `json:"network" bson:"network" validate:"network_exists"`
  44. IsPending string `json:"ispending" bson:"ispending"`
  45. IsEgressGateway string `json:"isegressgateway" bson:"isegressgateway"`
  46. IsIngressGateway string `json:"isingressgateway" bson:"isingressgateway"`
  47. EgressGatewayRanges []string `json:"egressgatewayranges" bson:"egressgatewayranges"`
  48. IngressGatewayRange string `json:"ingressgatewayrange" bson:"ingressgatewayrange"`
  49. PostChanges string `json:"postchanges" bson:"postchanges"`
  50. StaticIP string `json:"staticip" bson:"staticip"`
  51. StaticPubKey string `json:"staticpubkey" bson:"staticpubkey"`
  52. UDPHolePunch string `json:"udpholepunch" bson:"udpholepunch" validate:"checkyesorno"`
  53. }
  54. //TODO:
  55. //Not sure if below two methods are necessary. May want to revisit
  56. func (node *Node) SetLastModified() {
  57. node.LastModified = time.Now().Unix()
  58. }
  59. func (node *Node) SetLastCheckIn() {
  60. node.LastCheckIn = time.Now().Unix()
  61. }
  62. func (node *Node) SetLastPeerUpdate() {
  63. node.LastPeerUpdate = time.Now().Unix()
  64. }
  65. func (node *Node) SetID() {
  66. node.ID = node.MacAddress + "###" + node.Network
  67. }
  68. func (node *Node) SetExpirationDateTime() {
  69. node.ExpirationDateTime = time.Now().Unix() + TEN_YEARS_IN_SECONDS
  70. }
  71. func (node *Node) SetDefaultName() {
  72. if node.Name == "" {
  73. nodeid := StringWithCharset(5, charset)
  74. nodename := "node-" + nodeid
  75. node.Name = nodename
  76. }
  77. }
  78. func (node *Node) GetNetwork() (Network, error) {
  79. var network Network
  80. networkData, err := database.FetchRecord(database.NETWORKS_TABLE_NAME, node.Network)
  81. if err != nil {
  82. return network, err
  83. }
  84. if err = json.Unmarshal([]byte(networkData), &network); err != nil {
  85. return Network{}, err
  86. }
  87. return network, nil
  88. }
  89. //TODO: I dont know why this exists
  90. //This should exist on the node.go struct. I'm sure there was a reason?
  91. func (node *Node) SetDefaults() {
  92. //TODO: Maybe I should make Network a part of the node struct. Then we can just query the Network object for stuff.
  93. parentNetwork, _ := node.GetNetwork()
  94. node.ExpirationDateTime = time.Now().Unix() + TEN_YEARS_IN_SECONDS
  95. if node.ListenPort == 0 {
  96. node.ListenPort = parentNetwork.DefaultListenPort
  97. }
  98. if node.SaveConfig == "" {
  99. if parentNetwork.DefaultSaveConfig != "" {
  100. node.SaveConfig = parentNetwork.DefaultSaveConfig
  101. } else {
  102. node.SaveConfig = "yes"
  103. }
  104. }
  105. if node.Interface == "" {
  106. node.Interface = parentNetwork.DefaultInterface
  107. }
  108. if node.PersistentKeepalive == 0 {
  109. node.PersistentKeepalive = parentNetwork.DefaultKeepalive
  110. }
  111. if node.PostUp == "" {
  112. postup := parentNetwork.DefaultPostUp
  113. node.PostUp = postup
  114. }
  115. if node.StaticIP == "" {
  116. node.StaticIP = "no"
  117. }
  118. if node.StaticPubKey == "" {
  119. node.StaticPubKey = "no"
  120. }
  121. if node.UDPHolePunch == "" {
  122. node.UDPHolePunch = parentNetwork.DefaultUDPHolePunch
  123. if node.UDPHolePunch == "" {
  124. node.UDPHolePunch = "yes"
  125. }
  126. }
  127. node.CheckInInterval = parentNetwork.DefaultCheckInInterval
  128. node.SetLastModified()
  129. node.SetDefaultName()
  130. node.SetLastCheckIn()
  131. node.SetLastPeerUpdate()
  132. node.SetID()
  133. node.KeyUpdateTimeStamp = time.Now().Unix()
  134. }
  135. func (newNode *Node) Fill(currentNode *Node) {
  136. if newNode.ID == "" {
  137. newNode.ID = currentNode.ID
  138. }
  139. if newNode.Address == "" {
  140. newNode.Address = currentNode.Address
  141. }
  142. if newNode.Address6 == "" {
  143. newNode.Address6 = currentNode.Address6
  144. }
  145. if newNode.LocalAddress == "" {
  146. newNode.LocalAddress = currentNode.LocalAddress
  147. }
  148. if newNode.Name == "" {
  149. newNode.Name = currentNode.Name
  150. }
  151. if newNode.ListenPort == 0 {
  152. newNode.ListenPort = currentNode.ListenPort
  153. }
  154. if newNode.PublicKey == "" {
  155. newNode.PublicKey = currentNode.PublicKey
  156. } else {
  157. newNode.KeyUpdateTimeStamp = time.Now().Unix()
  158. }
  159. if newNode.Endpoint == "" {
  160. newNode.Endpoint = currentNode.Endpoint
  161. }
  162. if newNode.PostUp == "" {
  163. newNode.PostUp = currentNode.PostUp
  164. }
  165. if newNode.PostDown == "" {
  166. newNode.PostDown = currentNode.PostDown
  167. }
  168. if newNode.AllowedIPs == nil {
  169. newNode.AllowedIPs = currentNode.AllowedIPs
  170. }
  171. if newNode.PersistentKeepalive == 0 {
  172. newNode.PersistentKeepalive = currentNode.PersistentKeepalive
  173. }
  174. if newNode.SaveConfig == "" {
  175. newNode.SaveConfig = currentNode.SaveConfig
  176. }
  177. if newNode.AccessKey == "" {
  178. newNode.AccessKey = currentNode.AccessKey
  179. }
  180. if newNode.Interface == "" {
  181. newNode.Interface = currentNode.Interface
  182. }
  183. if newNode.LastModified == 0 {
  184. newNode.LastModified = currentNode.LastModified
  185. }
  186. if newNode.KeyUpdateTimeStamp == 0 {
  187. newNode.LastModified = currentNode.LastModified
  188. }
  189. if newNode.ExpirationDateTime == 0 {
  190. newNode.ExpirationDateTime = currentNode.ExpirationDateTime
  191. }
  192. if newNode.LastPeerUpdate == 0 {
  193. newNode.LastPeerUpdate = currentNode.LastPeerUpdate
  194. }
  195. if newNode.LastCheckIn == 0 {
  196. newNode.LastCheckIn = currentNode.LastCheckIn
  197. }
  198. if newNode.MacAddress == "" {
  199. newNode.MacAddress = currentNode.MacAddress
  200. }
  201. if newNode.CheckInInterval == 0 {
  202. newNode.CheckInInterval = currentNode.CheckInInterval
  203. }
  204. if newNode.Password != "" {
  205. err := bcrypt.CompareHashAndPassword([]byte(newNode.Password), []byte(currentNode.Password))
  206. if err != nil && currentNode.Password != newNode.Password {
  207. hash, err := bcrypt.GenerateFromPassword([]byte(newNode.Password), 5)
  208. if err == nil {
  209. newNode.Password = string(hash)
  210. }
  211. }
  212. } else {
  213. newNode.Password = currentNode.Password
  214. }
  215. if newNode.Network == "" {
  216. newNode.Network = currentNode.Network
  217. }
  218. if newNode.IsPending == "" {
  219. newNode.IsPending = currentNode.IsPending
  220. }
  221. if newNode.IsEgressGateway == "" {
  222. newNode.IsEgressGateway = currentNode.IsEgressGateway
  223. }
  224. if newNode.IsIngressGateway == "" {
  225. newNode.IsIngressGateway = currentNode.IsIngressGateway
  226. }
  227. if newNode.EgressGatewayRanges == nil {
  228. newNode.EgressGatewayRanges = currentNode.EgressGatewayRanges
  229. }
  230. if newNode.IngressGatewayRange == "" {
  231. newNode.IngressGatewayRange = currentNode.IngressGatewayRange
  232. }
  233. if newNode.StaticIP == "" {
  234. newNode.StaticIP = currentNode.StaticIP
  235. }
  236. if newNode.StaticIP == "" {
  237. newNode.StaticIP = currentNode.StaticIP
  238. }
  239. if newNode.StaticPubKey == "" {
  240. newNode.StaticPubKey = currentNode.StaticPubKey
  241. }
  242. if newNode.UDPHolePunch == "" {
  243. newNode.UDPHolePunch = currentNode.SaveConfig
  244. }
  245. newNode.PostChanges = "no"
  246. }
  247. func (currentNode *Node) Update(newNode *Node) error {
  248. log.Println("Node SaveConfig:", newNode.SaveConfig)
  249. newNode.Fill(currentNode)
  250. log.Println("Node SaveConfig 2:", newNode.SaveConfig)
  251. if err := newNode.Validate(true); err != nil {
  252. return err
  253. }
  254. newNode.SetID()
  255. if newNode.ID == currentNode.ID {
  256. if data, err := json.Marshal(newNode); err != nil {
  257. return err
  258. } else {
  259. newNode.SetLastModified()
  260. err = database.Insert(newNode.ID, string(data), database.NODES_TABLE_NAME)
  261. return err
  262. }
  263. }
  264. // copy values
  265. return errors.New("failed to update node " + newNode.MacAddress + ", cannot change macaddress.")
  266. }
  267. func StringWithCharset(length int, charset string) string {
  268. b := make([]byte, length)
  269. for i := range b {
  270. b[i] = charset[seededRand.Intn(len(charset))]
  271. }
  272. return string(b)
  273. }
  274. //Check for valid IPv4 address
  275. //Note: We dont handle IPv6 AT ALL!!!!! This definitely is needed at some point
  276. //But for iteration 1, lets just stick to IPv4. Keep it simple stupid.
  277. func IsIpv4Net(host string) bool {
  278. return net.ParseIP(host) != nil
  279. }
  280. func (node *Node) Validate(isUpdate bool) error {
  281. log.Println("Node SaveConfig:", node.SaveConfig)
  282. v := validator.New()
  283. _ = v.RegisterValidation("macaddress_unique", func(fl validator.FieldLevel) bool {
  284. if isUpdate {
  285. return true
  286. }
  287. isFieldUnique, _ := node.IsIDUnique()
  288. return isFieldUnique
  289. })
  290. _ = v.RegisterValidation("network_exists", func(fl validator.FieldLevel) bool {
  291. _, err := node.GetNetwork()
  292. return err == nil
  293. })
  294. _ = v.RegisterValidation("in_charset", func(fl validator.FieldLevel) bool {
  295. isgood := node.NameInNodeCharSet()
  296. return isgood
  297. })
  298. _ = v.RegisterValidation("checkyesorno", func(fl validator.FieldLevel) bool {
  299. return CheckYesOrNo(fl)
  300. })
  301. err := v.Struct(node)
  302. return err
  303. }
  304. func (node *Node) IsIDUnique() (bool, error) {
  305. record, err := database.FetchRecord(database.NODES_TABLE_NAME, node.ID)
  306. if err != nil {
  307. return false, err
  308. }
  309. return record == "", err
  310. }
  311. func (node *Node) NameInNodeCharSet() bool {
  312. charset := "abcdefghijklmnopqrstuvwxyz1234567890-"
  313. for _, char := range node.Name {
  314. if !strings.Contains(charset, strings.ToLower(string(char))) {
  315. return false
  316. }
  317. }
  318. return true
  319. }
  320. func GetAllNodes() ([]Node, error) {
  321. var nodes []Node
  322. collection, err := database.FetchRecords(database.NODES_TABLE_NAME)
  323. if err != nil {
  324. return []Node{}, err
  325. }
  326. for _, value := range collection {
  327. var node Node
  328. if err := json.Unmarshal([]byte(value), &node); err != nil {
  329. return []Node{}, err
  330. }
  331. // add node to our array
  332. nodes = append(nodes, node)
  333. }
  334. return nodes, nil
  335. }
  336. func GetNode(macaddress string, network string) (Node, error) {
  337. var node Node
  338. key, err := GetID(macaddress, network)
  339. if err != nil {
  340. return node, err
  341. }
  342. data, err := database.FetchRecord(database.NODES_TABLE_NAME, key)
  343. if err != nil {
  344. return node, err
  345. }
  346. if err = json.Unmarshal([]byte(data), &node); err != nil {
  347. return node, err
  348. }
  349. return node, err
  350. }
  351. func GetID(macaddress string, network string) (string, error) {
  352. if macaddress == "" || network == "" {
  353. return "", errors.New("unable to get record key")
  354. }
  355. return macaddress + "###" + network, nil
  356. }