node.go 27 KB

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