node.go 27 KB

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