node.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. package models
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "math/rand"
  6. "net"
  7. "strings"
  8. "time"
  9. "github.com/go-playground/validator/v10"
  10. "github.com/gravitl/netmaker/database"
  11. )
  12. const charset = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  13. var seededRand *rand.Rand = rand.New(
  14. rand.NewSource(time.Now().UnixNano()))
  15. //node struct
  16. type Node struct {
  17. ID string `json:"id,omitempty" bson:"id,omitempty"`
  18. Address string `json:"address" bson:"address" validate:"omitempty,ipv4"`
  19. Address6 string `json:"address6" bson:"address6" validate:"omitempty,ipv6"`
  20. LocalAddress string `json:"localaddress" bson:"localaddress" validate:"omitempty,ip"`
  21. Name string `json:"name" bson:"name" validate:"omitempty,max=12,in_charset"`
  22. ListenPort int32 `json:"listenport" bson:"listenport" validate:"omitempty,numeric,min=1024,max=65535"`
  23. PublicKey string `json:"publickey" bson:"publickey" validate:"required,base64"`
  24. Endpoint string `json:"endpoint" bson:"endpoint" validate:"required,ip"`
  25. PostUp string `json:"postup" bson:"postup"`
  26. PostDown string `json:"postdown" bson:"postdown"`
  27. AllowedIPs []string `json:"allowedips" bson:"allowedips"`
  28. PersistentKeepalive int32 `json:"persistentkeepalive" bson:"persistentkeepalive" validate:"omitempty,numeric,max=1000"`
  29. SaveConfig string `json:"saveconfig" bson:"saveconfig" validate:"checkyesorno"`
  30. AccessKey string `json:"accesskey" bson:"accesskey"`
  31. Interface string `json:"interface" bson:"interface"`
  32. LastModified int64 `json:"lastmodified" bson:"lastmodified"`
  33. KeyUpdateTimeStamp int64 `json:"keyupdatetimestamp" bson:"keyupdatetimestamp"`
  34. ExpirationDateTime int64 `json:"expdatetime" bson:"expdatetime"`
  35. LastPeerUpdate int64 `json:"lastpeerupdate" bson:"lastpeerupdate"`
  36. LastCheckIn int64 `json:"lastcheckin" bson:"lastcheckin"`
  37. MacAddress string `json:"macaddress" bson:"macaddress" validate:"required,mac,macaddress_unique"`
  38. CheckInInterval int32 `json:"checkininterval" bson:"checkininterval"`
  39. Password string `json:"password" bson:"password" validate:"required,min=6"`
  40. Network string `json:"network" bson:"network" validate:"network_exists"`
  41. IsPending bool `json:"ispending" bson:"ispending"`
  42. IsEgressGateway bool `json:"isegressgateway" bson:"isegressgateway"`
  43. IsIngressGateway bool `json:"isingressgateway" bson:"isingressgateway"`
  44. EgressGatewayRanges []string `json:"egressgatewayranges" bson:"egressgatewayranges"`
  45. IngressGatewayRange string `json:"ingressgatewayrange" bson:"ingressgatewayrange"`
  46. PostChanges string `json:"postchanges" bson:"postchanges"`
  47. StaticIP string `json:"staticip" bson:"staticip"`
  48. StaticPubKey string `json:"staticpubkey" bson:"staticpubkey"`
  49. UDPHolePunch string `json:"udpholepunch" bson:"udpholepunch" validate:"checkyesorno"`
  50. }
  51. //TODO:
  52. //Not sure if below two methods are necessary. May want to revisit
  53. func (node *Node) SetLastModified() {
  54. node.LastModified = time.Now().Unix()
  55. }
  56. func (node *Node) SetLastCheckIn() {
  57. node.LastCheckIn = time.Now().Unix()
  58. }
  59. func (node *Node) SetLastPeerUpdate() {
  60. node.LastPeerUpdate = time.Now().Unix()
  61. }
  62. func (node *Node) SetID() {
  63. node.ID = node.MacAddress + "###" + node.Network
  64. }
  65. func (node *Node) SetExpirationDateTime() {
  66. node.ExpirationDateTime = time.Unix(33174902665, 0).Unix()
  67. }
  68. func (node *Node) SetDefaultName() {
  69. if node.Name == "" {
  70. nodeid := StringWithCharset(5, charset)
  71. nodename := "node-" + nodeid
  72. node.Name = nodename
  73. }
  74. }
  75. func (node *Node) GetNetwork() (Network, error) {
  76. var network Network
  77. networkData, err := database.FetchRecord(database.NETWORKS_TABLE_NAME, node.Network)
  78. if err != nil {
  79. return network, err
  80. }
  81. if err = json.Unmarshal([]byte(networkData), &network); err != nil {
  82. return Network{}, err
  83. }
  84. return network, nil
  85. }
  86. //TODO: I dont know why this exists
  87. //This should exist on the node.go struct. I'm sure there was a reason?
  88. func (node *Node) SetDefaults() {
  89. //TODO: Maybe I should make Network a part of the node struct. Then we can just query the Network object for stuff.
  90. parentNetwork, _ := node.GetNetwork()
  91. node.ExpirationDateTime = time.Unix(33174902665, 0).Unix()
  92. if node.ListenPort == 0 {
  93. node.ListenPort = parentNetwork.DefaultListenPort
  94. }
  95. if node.SaveConfig == "" {
  96. if parentNetwork.DefaultSaveConfig != "" {
  97. node.SaveConfig = parentNetwork.DefaultSaveConfig
  98. }
  99. }
  100. if node.Interface == "" {
  101. node.Interface = parentNetwork.DefaultInterface
  102. }
  103. if node.PersistentKeepalive == 0 {
  104. node.PersistentKeepalive = parentNetwork.DefaultKeepalive
  105. }
  106. if node.PostUp == "" {
  107. postup := parentNetwork.DefaultPostUp
  108. node.PostUp = postup
  109. }
  110. if node.StaticIP == "" {
  111. node.StaticIP = "no"
  112. }
  113. if node.StaticPubKey == "" {
  114. node.StaticPubKey = "no"
  115. }
  116. if node.UDPHolePunch == "" {
  117. node.UDPHolePunch = parentNetwork.DefaultUDPHolePunch
  118. }
  119. node.CheckInInterval = parentNetwork.DefaultCheckInInterval
  120. node.SetLastModified()
  121. node.SetDefaultName()
  122. node.SetLastCheckIn()
  123. node.SetLastPeerUpdate()
  124. node.SetID()
  125. node.KeyUpdateTimeStamp = time.Now().Unix()
  126. }
  127. func (currentNode *Node) Update(newNode *Node) error {
  128. if err := newNode.Validate(true); err != nil {
  129. return err
  130. }
  131. newNode.SetID()
  132. if newNode.ID == currentNode.ID {
  133. if data, err := json.Marshal(newNode); err != nil {
  134. return err
  135. } else {
  136. newNode.SetLastModified()
  137. err = database.Insert(newNode.ID, string(data), database.NODES_TABLE_NAME)
  138. return err
  139. }
  140. }
  141. // copy values
  142. return errors.New("failed to update node " + newNode.MacAddress + ", cannot change macaddress.")
  143. }
  144. func StringWithCharset(length int, charset string) string {
  145. b := make([]byte, length)
  146. for i := range b {
  147. b[i] = charset[seededRand.Intn(len(charset))]
  148. }
  149. return string(b)
  150. }
  151. //Check for valid IPv4 address
  152. //Note: We dont handle IPv6 AT ALL!!!!! This definitely is needed at some point
  153. //But for iteration 1, lets just stick to IPv4. Keep it simple stupid.
  154. func IsIpv4Net(host string) bool {
  155. return net.ParseIP(host) != nil
  156. }
  157. func (node *Node) Validate(isUpdate bool) error {
  158. v := validator.New()
  159. _ = v.RegisterValidation("macaddress_unique", func(fl validator.FieldLevel) bool {
  160. if isUpdate {
  161. return true
  162. }
  163. isFieldUnique, _ := node.IsIDUnique()
  164. return isFieldUnique
  165. })
  166. _ = v.RegisterValidation("network_exists", func(fl validator.FieldLevel) bool {
  167. _, err := node.GetNetwork()
  168. return err == nil
  169. })
  170. _ = v.RegisterValidation("in_charset", func(fl validator.FieldLevel) bool {
  171. isgood := node.NameInNodeCharSet()
  172. return isgood
  173. })
  174. _ = v.RegisterValidation("checkyesorno", func(fl validator.FieldLevel) bool {
  175. return CheckYesOrNo(fl)
  176. })
  177. err := v.Struct(node)
  178. return err
  179. }
  180. func (node *Node) IsIDUnique() (bool, error) {
  181. record, err := database.FetchRecord(database.NODES_TABLE_NAME, node.ID)
  182. if err != nil {
  183. return false, err
  184. }
  185. return record == "", err
  186. }
  187. func (node *Node) NameInNodeCharSet() bool {
  188. charset := "abcdefghijklmnopqrstuvwxyz1234567890-"
  189. for _, char := range node.Name {
  190. if !strings.Contains(charset, strings.ToLower(string(char))) {
  191. return false
  192. }
  193. }
  194. return true
  195. }
  196. func GetAllNodes() ([]Node, error) {
  197. var nodes []Node
  198. collection, err := database.FetchRecords(database.NODES_TABLE_NAME)
  199. if err != nil {
  200. return []Node{}, err
  201. }
  202. for _, value := range collection {
  203. var node Node
  204. if err := json.Unmarshal([]byte(value), &node); err != nil {
  205. return []Node{}, err
  206. }
  207. // add node to our array
  208. nodes = append(nodes, node)
  209. }
  210. return nodes, nil
  211. }