node.go 24 KB

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