node.go 27 KB

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