node.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. package models
  2. import (
  3. "bytes"
  4. "math/rand"
  5. "net"
  6. "strings"
  7. "sync"
  8. "time"
  9. "github.com/google/uuid"
  10. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  11. )
  12. type NodeStatus string
  13. const (
  14. OnlineSt NodeStatus = "online"
  15. OfflineSt NodeStatus = "offline"
  16. WarningSt NodeStatus = "warning"
  17. ErrorSt NodeStatus = "error"
  18. UnKnown NodeStatus = "unknown"
  19. Disconnected NodeStatus = "disconnected"
  20. )
  21. // LastCheckInThreshold - if node's checkin more than this threshold,then node is declared as offline
  22. const LastCheckInThreshold = time.Minute * 10
  23. const (
  24. // NODE_SERVER_NAME - the default server name
  25. NODE_SERVER_NAME = "netmaker"
  26. // MAX_NAME_LENGTH - max name length of node
  27. MAX_NAME_LENGTH = 62
  28. // == ACTIONS == (can only be set by server)
  29. // NODE_DELETE - delete node action
  30. NODE_DELETE = "delete"
  31. // NODE_IS_PENDING - node pending status
  32. NODE_IS_PENDING = "pending"
  33. // NODE_NOOP - node no op action
  34. NODE_NOOP = "noop"
  35. // NODE_FORCE_UPDATE - indicates a node should pull all changes
  36. NODE_FORCE_UPDATE = "force"
  37. // FIREWALL_IPTABLES - indicates that iptables is the firewall in use
  38. FIREWALL_IPTABLES = "iptables"
  39. // FIREWALL_NFTABLES - indicates nftables is in use (Linux only)
  40. FIREWALL_NFTABLES = "nftables"
  41. // FIREWALL_NONE - indicates that no supported firewall in use
  42. FIREWALL_NONE = "none"
  43. )
  44. var seededRand *rand.Rand = rand.New(
  45. rand.NewSource(time.Now().UnixNano()))
  46. // NodeCheckin - struct for node checkins with server
  47. type NodeCheckin struct {
  48. Version string
  49. Connected bool
  50. Ifaces []Iface
  51. }
  52. // Iface struct for local interfaces of a node
  53. type Iface struct {
  54. Name string `json:"name"`
  55. Address net.IPNet `json:"address"`
  56. AddressString string `json:"addressString"`
  57. }
  58. // CommonNode - represents a commonn node data elements shared by netmaker and netclient
  59. type CommonNode struct {
  60. ID uuid.UUID `json:"id" yaml:"id"`
  61. HostID uuid.UUID `json:"hostid" yaml:"hostid"`
  62. Network string `json:"network" yaml:"network"`
  63. NetworkRange net.IPNet `json:"networkrange" yaml:"networkrange" swaggertype:"primitive,integer"`
  64. NetworkRange6 net.IPNet `json:"networkrange6" yaml:"networkrange6" swaggertype:"primitive,number"`
  65. Server string `json:"server" yaml:"server"`
  66. Connected bool `json:"connected" yaml:"connected"`
  67. Address net.IPNet `json:"address" yaml:"address"`
  68. Address6 net.IPNet `json:"address6" yaml:"address6"`
  69. Action string `json:"action" yaml:"action"`
  70. LocalAddress net.IPNet `json:"localaddress" yaml:"localaddress"`
  71. IsEgressGateway bool `json:"isegressgateway" yaml:"isegressgateway"`
  72. EgressGatewayRanges []string `json:"egressgatewayranges" yaml:"egressgatewayranges"`
  73. IsIngressGateway bool `json:"isingressgateway" yaml:"isingressgateway"`
  74. IsRelayed bool `json:"isrelayed" yaml:"isrelayed"`
  75. RelayedBy string `json:"relayedby" yaml:"relayedby"`
  76. IsRelay bool `json:"isrelay" yaml:"isrelay"`
  77. IsGw bool `json:"is_gw" yaml:"is_gw"`
  78. RelayedNodes []string `json:"relaynodes" yaml:"relayedNodes"`
  79. IngressDNS string `json:"ingressdns" yaml:"ingressdns"`
  80. DNSOn bool `json:"dnson" yaml:"dnson"`
  81. }
  82. // Node - a model of a network node
  83. type Node struct {
  84. CommonNode
  85. PendingDelete bool `json:"pendingdelete" bson:"pendingdelete" yaml:"pendingdelete"`
  86. LastModified time.Time `json:"lastmodified" bson:"lastmodified" yaml:"lastmodified"`
  87. LastCheckIn time.Time `json:"lastcheckin" bson:"lastcheckin" yaml:"lastcheckin"`
  88. LastPeerUpdate time.Time `json:"lastpeerupdate" bson:"lastpeerupdate" yaml:"lastpeerupdate"`
  89. ExpirationDateTime time.Time `json:"expdatetime" bson:"expdatetime" yaml:"expdatetime"`
  90. EgressGatewayNatEnabled bool `json:"egressgatewaynatenabled" bson:"egressgatewaynatenabled" yaml:"egressgatewaynatenabled"`
  91. EgressGatewayRequest EgressGatewayRequest `json:"egressgatewayrequest" bson:"egressgatewayrequest" yaml:"egressgatewayrequest"`
  92. IngressGatewayRange string `json:"ingressgatewayrange" bson:"ingressgatewayrange" yaml:"ingressgatewayrange"`
  93. IngressGatewayRange6 string `json:"ingressgatewayrange6" bson:"ingressgatewayrange6" yaml:"ingressgatewayrange6"`
  94. IngressPersistentKeepalive int32 `json:"ingresspersistentkeepalive" bson:"ingresspersistentkeepalive" yaml:"ingresspersistentkeepalive"`
  95. IngressMTU int32 `json:"ingressmtu" bson:"ingressmtu" yaml:"ingressmtu"`
  96. Metadata string `json:"metadata"`
  97. // == PRO ==
  98. DefaultACL string `json:"defaultacl,omitempty" bson:"defaultacl,omitempty" yaml:"defaultacl,omitempty" validate:"checkyesornoorunset"`
  99. OwnerID string `json:"ownerid,omitempty" bson:"ownerid,omitempty" yaml:"ownerid,omitempty"`
  100. IsFailOver bool `json:"is_fail_over" yaml:"is_fail_over"`
  101. FailOverPeers map[string]struct{} `json:"fail_over_peers" yaml:"fail_over_peers"`
  102. FailedOverBy uuid.UUID `json:"failed_over_by" yaml:"failed_over_by"`
  103. IsInternetGateway bool `json:"isinternetgateway" yaml:"isinternetgateway"`
  104. InetNodeReq InetNodeReq `json:"inet_node_req" yaml:"inet_node_req"`
  105. InternetGwID string `json:"internetgw_node_id" yaml:"internetgw_node_id"`
  106. AdditionalRagIps []net.IP `json:"additional_rag_ips" yaml:"additional_rag_ips" swaggertype:"array,number"`
  107. Tags map[TagID]struct{} `json:"tags" yaml:"tags"`
  108. IsStatic bool `json:"is_static"`
  109. IsUserNode bool `json:"is_user_node"`
  110. StaticNode ExtClient `json:"static_node"`
  111. Status NodeStatus `json:"node_status"`
  112. Mutex *sync.Mutex `json:"-"`
  113. EgressDetails EgressDetails `json:"-"`
  114. }
  115. type EgressDetails struct {
  116. EgressGatewayNatEnabled bool
  117. EgressGatewayRequest EgressGatewayRequest
  118. IsEgressGateway bool
  119. EgressGatewayRanges []string
  120. }
  121. // LegacyNode - legacy struct for node model
  122. type LegacyNode struct {
  123. ID string `json:"id,omitempty" bson:"id,omitempty" yaml:"id,omitempty" validate:"required,min=5,id_unique"`
  124. Address string `json:"address" bson:"address" yaml:"address" validate:"omitempty,ipv4"`
  125. Address6 string `json:"address6" bson:"address6" yaml:"address6" validate:"omitempty,ipv6"`
  126. LocalAddress string `json:"localaddress" bson:"localaddress" yaml:"localaddress" validate:"omitempty"`
  127. Interfaces []Iface `json:"interfaces" yaml:"interfaces"`
  128. Name string `json:"name" bson:"name" yaml:"name" validate:"omitempty,max=62,in_charset"`
  129. NetworkSettings Network `json:"networksettings" bson:"networksettings" yaml:"networksettings" validate:"-"`
  130. ListenPort int32 `json:"listenport" bson:"listenport" yaml:"listenport" validate:"omitempty,numeric,min=1024,max=65535"`
  131. LocalListenPort int32 `json:"locallistenport" bson:"locallistenport" yaml:"locallistenport" validate:"numeric,min=0,max=65535"`
  132. PublicKey string `json:"publickey" bson:"publickey" yaml:"publickey" validate:"required,base64"`
  133. Endpoint string `json:"endpoint" bson:"endpoint" yaml:"endpoint" validate:"required,ip"`
  134. AllowedIPs []string `json:"allowedips" bson:"allowedips" yaml:"allowedips"`
  135. PersistentKeepalive int32 `json:"persistentkeepalive" bson:"persistentkeepalive" yaml:"persistentkeepalive" validate:"omitempty,numeric,max=1000"`
  136. IsHub string `json:"ishub" bson:"ishub" yaml:"ishub" validate:"checkyesorno"`
  137. AccessKey string `json:"accesskey" bson:"accesskey" yaml:"accesskey"`
  138. Interface string `json:"interface" bson:"interface" yaml:"interface"`
  139. LastModified int64 `json:"lastmodified" bson:"lastmodified" yaml:"lastmodified" swaggertype:"primitive,integer" format:"int64"`
  140. ExpirationDateTime int64 `json:"expdatetime" bson:"expdatetime" yaml:"expdatetime" swaggertype:"primitive,integer" format:"int64"`
  141. LastPeerUpdate int64 `json:"lastpeerupdate" bson:"lastpeerupdate" yaml:"lastpeerupdate" swaggertype:"primitive,integer" format:"int64"`
  142. LastCheckIn int64 `json:"lastcheckin" bson:"lastcheckin" yaml:"lastcheckin" swaggertype:"primitive,integer" format:"int64"`
  143. MacAddress string `json:"macaddress" bson:"macaddress" yaml:"macaddress"`
  144. Password string `json:"password" bson:"password" yaml:"password" validate:"required,min=6"`
  145. Network string `json:"network" bson:"network" yaml:"network" validate:"network_exists"`
  146. IsRelayed string `json:"isrelayed" bson:"isrelayed" yaml:"isrelayed"`
  147. IsPending string `json:"ispending" bson:"ispending" yaml:"ispending"`
  148. IsRelay string `json:"isrelay" bson:"isrelay" yaml:"isrelay" validate:"checkyesorno"`
  149. IsDocker string `json:"isdocker" bson:"isdocker" yaml:"isdocker" validate:"checkyesorno"`
  150. IsK8S string `json:"isk8s" bson:"isk8s" yaml:"isk8s" validate:"checkyesorno"`
  151. IsEgressGateway string `json:"isegressgateway" bson:"isegressgateway" yaml:"isegressgateway" validate:"checkyesorno"`
  152. IsIngressGateway string `json:"isingressgateway" bson:"isingressgateway" yaml:"isingressgateway" validate:"checkyesorno"`
  153. EgressGatewayRanges []string `json:"egressgatewayranges" bson:"egressgatewayranges" yaml:"egressgatewayranges"`
  154. EgressGatewayNatEnabled string `json:"egressgatewaynatenabled" bson:"egressgatewaynatenabled" yaml:"egressgatewaynatenabled"`
  155. EgressGatewayRequest EgressGatewayRequest `json:"egressgatewayrequest" bson:"egressgatewayrequest" yaml:"egressgatewayrequest"`
  156. RelayAddrs []string `json:"relayaddrs" bson:"relayaddrs" yaml:"relayaddrs"`
  157. FailoverNode string `json:"failovernode" bson:"failovernode" yaml:"failovernode"`
  158. IngressGatewayRange string `json:"ingressgatewayrange" bson:"ingressgatewayrange" yaml:"ingressgatewayrange"`
  159. IngressGatewayRange6 string `json:"ingressgatewayrange6" bson:"ingressgatewayrange6" yaml:"ingressgatewayrange6"`
  160. // IsStatic - refers to if the Endpoint is set manually or dynamically
  161. IsStatic string `json:"isstatic" bson:"isstatic" yaml:"isstatic" validate:"checkyesorno"`
  162. UDPHolePunch string `json:"udpholepunch" bson:"udpholepunch" yaml:"udpholepunch" validate:"checkyesorno"`
  163. DNSOn string `json:"dnson" bson:"dnson" yaml:"dnson" validate:"checkyesorno"`
  164. IsServer string `json:"isserver" bson:"isserver" yaml:"isserver" validate:"checkyesorno"`
  165. Action string `json:"action" bson:"action" yaml:"action"`
  166. IPForwarding string `json:"ipforwarding" bson:"ipforwarding" yaml:"ipforwarding" validate:"checkyesorno"`
  167. OS string `json:"os" bson:"os" yaml:"os"`
  168. MTU int32 `json:"mtu" bson:"mtu" yaml:"mtu"`
  169. Version string `json:"version" bson:"version" yaml:"version"`
  170. Server string `json:"server" bson:"server" yaml:"server"`
  171. TrafficKeys TrafficKeys `json:"traffickeys" bson:"traffickeys" yaml:"traffickeys"`
  172. FirewallInUse string `json:"firewallinuse" bson:"firewallinuse" yaml:"firewallinuse"`
  173. InternetGateway string `json:"internetgateway" bson:"internetgateway" yaml:"internetgateway"`
  174. Connected string `json:"connected" bson:"connected" yaml:"connected" validate:"checkyesorno"`
  175. // == PRO ==
  176. DefaultACL string `json:"defaultacl,omitempty" bson:"defaultacl,omitempty" yaml:"defaultacl,omitempty" validate:"checkyesornoorunset"`
  177. OwnerID string `json:"ownerid,omitempty" bson:"ownerid,omitempty" yaml:"ownerid,omitempty"`
  178. Failover string `json:"failover" bson:"failover" yaml:"failover" validate:"checkyesorno"`
  179. }
  180. // NodesArray - used for node sorting
  181. type NodesArray []Node
  182. // NodesArray.Len - gets length of node array
  183. func (a NodesArray) Len() int { return len(a) }
  184. // NodesArray.Less - gets returns lower rank of two node addressesFill
  185. func (a NodesArray) Less(i, j int) bool {
  186. return isLess(a[i].Address.IP.String(), a[j].Address.IP.String())
  187. }
  188. // NodesArray.Swap - swaps two nodes in array
  189. func (a NodesArray) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  190. func isLess(ipA string, ipB string) bool {
  191. ipNetA := net.ParseIP(ipA)
  192. ipNetB := net.ParseIP(ipB)
  193. return bytes.Compare(ipNetA, ipNetB) < 0
  194. }
  195. // Node.PrimaryAddress - return ipv4 address if present, else return ipv6
  196. func (node *Node) PrimaryAddressIPNet() net.IPNet {
  197. if node.Address.IP != nil {
  198. return node.Address
  199. }
  200. return node.Address6
  201. }
  202. // Node.PrimaryAddress - return ipv4 address if present, else return ipv6
  203. func (node *Node) PrimaryAddress() string {
  204. if node.Address.IP != nil {
  205. return node.Address.IP.String()
  206. }
  207. return node.Address6.IP.String()
  208. }
  209. func (node *Node) AddressIPNet4() net.IPNet {
  210. return net.IPNet{
  211. IP: node.Address.IP,
  212. Mask: net.CIDRMask(32, 32),
  213. }
  214. }
  215. func (node *Node) AddressIPNet6() net.IPNet {
  216. return net.IPNet{
  217. IP: node.Address6.IP,
  218. Mask: net.CIDRMask(128, 128),
  219. }
  220. }
  221. // ExtClient.PrimaryAddress - returns ipv4 IPNet format
  222. func (extPeer *ExtClient) AddressIPNet4() net.IPNet {
  223. return net.IPNet{
  224. IP: net.ParseIP(extPeer.Address),
  225. Mask: net.CIDRMask(32, 32),
  226. }
  227. }
  228. // ExtClient.AddressIPNet6 - return ipv6 IPNet format
  229. func (extPeer *ExtClient) AddressIPNet6() net.IPNet {
  230. return net.IPNet{
  231. IP: net.ParseIP(extPeer.Address6),
  232. Mask: net.CIDRMask(128, 128),
  233. }
  234. }
  235. // Node.PrimaryNetworkRange - returns node's parent network, returns ipv4 address if present, else return ipv6
  236. func (node *Node) PrimaryNetworkRange() net.IPNet {
  237. if node.NetworkRange.IP != nil {
  238. return node.NetworkRange
  239. }
  240. return node.NetworkRange6
  241. }
  242. // Node.SetDefaultConnected
  243. func (node *Node) SetDefaultConnected() {
  244. node.Connected = true
  245. }
  246. // Node.SetDefaultACL
  247. func (node *LegacyNode) SetDefaultACL() {
  248. if node.DefaultACL == "" {
  249. node.DefaultACL = "yes"
  250. }
  251. }
  252. // Node.SetDefaultMTU - sets default MTU of a node
  253. func (node *LegacyNode) SetDefaultMTU() {
  254. if node.MTU == 0 {
  255. node.MTU = 1280
  256. }
  257. }
  258. // Node.SetDefaultNFTablesPresent - sets default for nftables check
  259. func (node *LegacyNode) SetDefaultNFTablesPresent() {
  260. if node.FirewallInUse == "" {
  261. node.FirewallInUse = FIREWALL_IPTABLES // default to iptables
  262. }
  263. }
  264. // Node.SetDefaultIsRelayed - set default is relayed
  265. func (node *LegacyNode) SetDefaultIsRelayed() {
  266. if node.IsRelayed == "" {
  267. node.IsRelayed = "no"
  268. }
  269. }
  270. // Node.SetDefaultIsRelayed - set default is relayed
  271. func (node *LegacyNode) SetDefaultIsHub() {
  272. if node.IsHub == "" {
  273. node.IsHub = "no"
  274. }
  275. }
  276. // Node.SetDefaultIsRelay - set default isrelay
  277. func (node *LegacyNode) SetDefaultIsRelay() {
  278. if node.IsRelay == "" {
  279. node.IsRelay = "no"
  280. }
  281. }
  282. // Node.SetDefaultIsDocker - set default isdocker
  283. func (node *LegacyNode) SetDefaultIsDocker() {
  284. if node.IsDocker == "" {
  285. node.IsDocker = "no"
  286. }
  287. }
  288. // Node.SetDefaultIsK8S - set default isk8s
  289. func (node *LegacyNode) SetDefaultIsK8S() {
  290. if node.IsK8S == "" {
  291. node.IsK8S = "no"
  292. }
  293. }
  294. // Node.SetDefaultEgressGateway - sets default egress gateway status
  295. func (node *LegacyNode) SetDefaultEgressGateway() {
  296. if node.IsEgressGateway == "" {
  297. node.IsEgressGateway = "no"
  298. }
  299. }
  300. // Node.SetDefaultIngressGateway - sets default ingress gateway status
  301. func (node *LegacyNode) SetDefaultIngressGateway() {
  302. if node.IsIngressGateway == "" {
  303. node.IsIngressGateway = "no"
  304. }
  305. }
  306. // Node.SetDefaultAction - sets default action status
  307. func (node *LegacyNode) SetDefaultAction() {
  308. if node.Action == "" {
  309. node.Action = NODE_NOOP
  310. }
  311. }
  312. // Node.SetRoamingDefault - sets default roaming status
  313. //func (node *Node) SetRoamingDefault() {
  314. // if node.Roaming == "" {
  315. // node.Roaming = "yes"
  316. // }
  317. //}
  318. // Node.SetIPForwardingDefault - set ip forwarding default
  319. func (node *LegacyNode) SetIPForwardingDefault() {
  320. if node.IPForwarding == "" {
  321. node.IPForwarding = "yes"
  322. }
  323. }
  324. // Node.SetDNSOnDefault - sets dns on default
  325. func (node *LegacyNode) SetDNSOnDefault() {
  326. if node.DNSOn == "" {
  327. node.DNSOn = "yes"
  328. }
  329. }
  330. // Node.SetIsServerDefault - sets node isserver default
  331. func (node *LegacyNode) SetIsServerDefault() {
  332. if node.IsServer != "yes" {
  333. node.IsServer = "no"
  334. }
  335. }
  336. // Node.SetIsStaticDefault - set is static default
  337. func (node *LegacyNode) SetIsStaticDefault() {
  338. if node.IsServer == "yes" {
  339. node.IsStatic = "yes"
  340. } else if node.IsStatic != "yes" {
  341. node.IsStatic = "no"
  342. }
  343. }
  344. // Node.SetLastModified - set last modified initial time
  345. func (node *Node) SetLastModified() {
  346. node.LastModified = time.Now().UTC()
  347. }
  348. // Node.SetLastCheckIn - set checkin time of node
  349. func (node *Node) SetLastCheckIn() {
  350. node.LastCheckIn = time.Now().UTC()
  351. }
  352. // Node.SetLastPeerUpdate - sets last peer update time
  353. func (node *Node) SetLastPeerUpdate() {
  354. node.LastPeerUpdate = time.Now().UTC()
  355. }
  356. // Node.SetExpirationDateTime - sets node expiry time
  357. func (node *Node) SetExpirationDateTime() {
  358. if node.ExpirationDateTime.IsZero() {
  359. node.ExpirationDateTime = time.Now().AddDate(100, 1, 0)
  360. }
  361. }
  362. // Node.SetDefaultName - sets a random name to node
  363. func (node *LegacyNode) SetDefaultName() {
  364. if node.Name == "" {
  365. node.Name = GenerateNodeName()
  366. }
  367. }
  368. // Node.SetDefaultFailover - sets default value of failover status to no if not set
  369. func (node *LegacyNode) SetDefaultFailover() {
  370. if node.Failover == "" {
  371. node.Failover = "no"
  372. }
  373. }
  374. // Node.Fill - fills other node data into calling node data if not set on calling node (skips DNSOn)
  375. func (newNode *Node) Fill(
  376. currentNode *Node,
  377. isPro bool,
  378. ) { // TODO add new field for nftables present
  379. newNode.ID = currentNode.ID
  380. newNode.HostID = currentNode.HostID
  381. // Revisit the logic for boolean values
  382. // TODO ---- !!!!!!!!!!!!!!!!!!!!!!!!!!!!
  383. // TODO ---- !!!!!!!!!!!!!!!!!!!!!!!!!!
  384. if newNode.Address.String() == "" {
  385. newNode.Address = currentNode.Address
  386. }
  387. if newNode.Address6.String() == "" {
  388. newNode.Address6 = currentNode.Address6
  389. }
  390. if newNode.LastModified != currentNode.LastModified {
  391. newNode.LastModified = currentNode.LastModified
  392. }
  393. if newNode.ExpirationDateTime.IsZero() {
  394. newNode.ExpirationDateTime = currentNode.ExpirationDateTime
  395. }
  396. if newNode.LastPeerUpdate.IsZero() {
  397. newNode.LastPeerUpdate = currentNode.LastPeerUpdate
  398. }
  399. if newNode.LastCheckIn.IsZero() {
  400. newNode.LastCheckIn = currentNode.LastCheckIn
  401. }
  402. if newNode.Network == "" {
  403. newNode.Network = currentNode.Network
  404. }
  405. if newNode.IsIngressGateway != currentNode.IsIngressGateway {
  406. newNode.IsIngressGateway = currentNode.IsIngressGateway
  407. }
  408. if newNode.IngressGatewayRange == "" {
  409. newNode.IngressGatewayRange = currentNode.IngressGatewayRange
  410. }
  411. if newNode.IngressGatewayRange6 == "" {
  412. newNode.IngressGatewayRange6 = currentNode.IngressGatewayRange6
  413. }
  414. if newNode.Action == "" {
  415. newNode.Action = currentNode.Action
  416. }
  417. if newNode.RelayedNodes == nil {
  418. newNode.RelayedNodes = currentNode.RelayedNodes
  419. }
  420. if newNode.IsRelay != currentNode.IsRelay && isPro {
  421. newNode.IsRelay = currentNode.IsRelay
  422. }
  423. if newNode.IsRelayed == currentNode.IsRelayed && isPro {
  424. newNode.IsRelayed = currentNode.IsRelayed
  425. }
  426. if newNode.Server == "" {
  427. newNode.Server = currentNode.Server
  428. }
  429. if newNode.DefaultACL == "" {
  430. newNode.DefaultACL = currentNode.DefaultACL
  431. }
  432. if newNode.IsFailOver != currentNode.IsFailOver {
  433. newNode.IsFailOver = currentNode.IsFailOver
  434. }
  435. }
  436. // StringWithCharset - returns random string inside defined charset
  437. func StringWithCharset(length int, charset string) string {
  438. b := make([]byte, length)
  439. for i := range b {
  440. b[i] = charset[seededRand.Intn(len(charset))]
  441. }
  442. return string(b)
  443. }
  444. // IsIpv4Net - check for valid IPv4 address
  445. // Note: We dont handle IPv6 AT ALL!!!!! This definitely is needed at some point
  446. // But for iteration 1, lets just stick to IPv4. Keep it simple stupid.
  447. func IsIpv4Net(host string) bool {
  448. return net.ParseIP(host) != nil
  449. }
  450. // Node.NameInNodeCharset - returns if name is in charset below or not
  451. func (node *LegacyNode) NameInNodeCharSet() bool {
  452. charset := "abcdefghijklmnopqrstuvwxyz1234567890-"
  453. for _, char := range node.Name {
  454. if !strings.Contains(charset, strings.ToLower(string(char))) {
  455. return false
  456. }
  457. }
  458. return true
  459. }
  460. // == PRO ==
  461. // Node.DoesACLAllow - checks if default ACL on node is "yes"
  462. func (node *Node) DoesACLAllow() bool {
  463. return node.DefaultACL == "yes"
  464. }
  465. // Node.DoesACLDeny - checks if default ACL on node is "no"
  466. func (node *Node) DoesACLDeny() bool {
  467. return node.DefaultACL == "no"
  468. }
  469. func (ln *LegacyNode) ConvertToNewNode() (*Host, *Node) {
  470. var node Node
  471. //host:= logic.GetHost(node.HostID)
  472. var host Host
  473. if host.ID.String() == "" {
  474. host.ID = uuid.New()
  475. host.FirewallInUse = ln.FirewallInUse
  476. host.Version = ln.Version
  477. host.IPForwarding = parseBool(ln.IPForwarding)
  478. host.HostPass = ln.Password
  479. host.Name = ln.Name
  480. host.ListenPort = int(ln.ListenPort)
  481. host.MTU = int(ln.MTU)
  482. host.PublicKey, _ = wgtypes.ParseKey(ln.PublicKey)
  483. host.MacAddress, _ = net.ParseMAC(ln.MacAddress)
  484. host.TrafficKeyPublic = ln.TrafficKeys.Mine
  485. id, _ := uuid.Parse(ln.ID)
  486. host.Nodes = append(host.Nodes, id.String())
  487. host.Interfaces = ln.Interfaces
  488. host.EndpointIP = net.ParseIP(ln.Endpoint)
  489. // host.ProxyEnabled = ln.Proxy // this will always be false..
  490. }
  491. id, _ := uuid.Parse(ln.ID)
  492. node.ID = id
  493. node.Network = ln.Network
  494. if _, cidr, err := net.ParseCIDR(ln.NetworkSettings.AddressRange); err == nil {
  495. node.NetworkRange = *cidr
  496. }
  497. if _, cidr, err := net.ParseCIDR(ln.NetworkSettings.AddressRange6); err == nil {
  498. node.NetworkRange6 = *cidr
  499. }
  500. node.Server = ln.Server
  501. node.Connected = parseBool(ln.Connected)
  502. if ln.Address != "" {
  503. node.Address = net.IPNet{
  504. IP: net.ParseIP(ln.Address),
  505. Mask: net.CIDRMask(32, 32),
  506. }
  507. }
  508. if ln.Address6 != "" {
  509. node.Address = net.IPNet{
  510. IP: net.ParseIP(ln.Address6),
  511. Mask: net.CIDRMask(128, 128),
  512. }
  513. }
  514. node.Action = ln.Action
  515. node.IsIngressGateway = parseBool(ln.IsIngressGateway)
  516. node.DNSOn = parseBool(ln.DNSOn)
  517. return &host, &node
  518. }
  519. // Node.Legacy converts node to legacy format
  520. func (n *Node) Legacy(h *Host, s *ServerConfig, net *Network) *LegacyNode {
  521. l := LegacyNode{}
  522. l.ID = n.ID.String()
  523. //l.HostID = h.ID.String()
  524. l.Address = n.Address.String()
  525. l.Address6 = n.Address6.String()
  526. l.Interfaces = h.Interfaces
  527. l.Name = h.Name
  528. l.NetworkSettings = *net
  529. l.ListenPort = int32(h.ListenPort)
  530. l.PublicKey = h.PublicKey.String()
  531. l.Endpoint = h.EndpointIP.String()
  532. //l.AllowedIPs =
  533. l.AccessKey = ""
  534. l.Interface = WIREGUARD_INTERFACE
  535. //l.LastModified =
  536. //l.ExpirationDateTime
  537. //l.LastPeerUpdate
  538. //l.LastCheckIn
  539. l.MacAddress = h.MacAddress.String()
  540. l.Password = h.HostPass
  541. l.Network = n.Network
  542. //l.IsRelayed = formatBool(n.Is)
  543. //l.IsRelay = formatBool(n.IsRelay)
  544. //l.IsDocker = formatBool(n.IsDocker)
  545. //l.IsK8S = formatBool(n.IsK8S)
  546. l.IsIngressGateway = formatBool(n.IsIngressGateway)
  547. //l.EgressGatewayRanges = n.EgressGatewayRanges
  548. //l.EgressGatewayNatEnabled = n.EgressGatewayNatEnabled
  549. //l.RelayAddrs = n.RelayAddrs
  550. //l.FailoverNode = n.FailoverNode
  551. //l.IngressGatewayRange = n.IngressGatewayRange
  552. //l.IngressGatewayRange6 = n.IngressGatewayRange6
  553. l.IsStatic = formatBool(h.IsStatic)
  554. l.UDPHolePunch = formatBool(true)
  555. l.DNSOn = formatBool(n.DNSOn)
  556. l.Action = n.Action
  557. l.IPForwarding = formatBool(h.IPForwarding)
  558. l.OS = h.OS
  559. l.MTU = int32(h.MTU)
  560. l.Version = h.Version
  561. l.Server = n.Server
  562. l.TrafficKeys.Mine = h.TrafficKeyPublic
  563. l.TrafficKeys.Server = s.TrafficKey
  564. l.FirewallInUse = h.FirewallInUse
  565. l.Connected = formatBool(n.Connected)
  566. //l.PendingDelete = formatBool(n.PendingDelete)
  567. l.DefaultACL = n.DefaultACL
  568. l.OwnerID = n.OwnerID
  569. //l.Failover = n.Failover
  570. return &l
  571. }
  572. // Node.NetworkSettings updates a node with network settings
  573. func (node *Node) NetworkSettings(n Network) {
  574. _, cidr, err := net.ParseCIDR(n.AddressRange)
  575. if err == nil {
  576. node.NetworkRange = *cidr
  577. }
  578. _, cidr, err = net.ParseCIDR(n.AddressRange6)
  579. if err == nil {
  580. node.NetworkRange6 = *cidr
  581. }
  582. }
  583. func parseBool(s string) bool {
  584. b := false
  585. if s == "yes" {
  586. b = true
  587. }
  588. return b
  589. }
  590. func formatBool(b bool) string {
  591. s := "no"
  592. if b {
  593. s = "yes"
  594. }
  595. return s
  596. }