backend.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. // Copyright 2019 the Kilo authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package k8s
  15. import (
  16. "context"
  17. "encoding/json"
  18. "errors"
  19. "fmt"
  20. "net"
  21. "path"
  22. "strconv"
  23. "strings"
  24. "time"
  25. v1 "k8s.io/api/core/v1"
  26. apiextensions "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
  27. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  28. "k8s.io/apimachinery/pkg/labels"
  29. "k8s.io/apimachinery/pkg/types"
  30. "k8s.io/apimachinery/pkg/util/strategicpatch"
  31. "k8s.io/apimachinery/pkg/util/validation"
  32. v1informers "k8s.io/client-go/informers/core/v1"
  33. "k8s.io/client-go/kubernetes"
  34. v1listers "k8s.io/client-go/listers/core/v1"
  35. "k8s.io/client-go/tools/cache"
  36. "github.com/squat/kilo/pkg/k8s/apis/kilo/v1alpha1"
  37. kiloclient "github.com/squat/kilo/pkg/k8s/clientset/versioned"
  38. v1alpha1informers "github.com/squat/kilo/pkg/k8s/informers/kilo/v1alpha1"
  39. v1alpha1listers "github.com/squat/kilo/pkg/k8s/listers/kilo/v1alpha1"
  40. "github.com/squat/kilo/pkg/mesh"
  41. "github.com/squat/kilo/pkg/wireguard"
  42. )
  43. const (
  44. // Backend is the name of this mesh backend.
  45. Backend = "kubernetes"
  46. endpointAnnotationKey = "kilo.squat.ai/endpoint"
  47. forceEndpointAnnotationKey = "kilo.squat.ai/force-endpoint"
  48. forceInternalIPAnnotationKey = "kilo.squat.ai/force-internal-ip"
  49. internalIPAnnotationKey = "kilo.squat.ai/internal-ip"
  50. keyAnnotationKey = "kilo.squat.ai/key"
  51. lastSeenAnnotationKey = "kilo.squat.ai/last-seen"
  52. leaderAnnotationKey = "kilo.squat.ai/leader"
  53. locationAnnotationKey = "kilo.squat.ai/location"
  54. persistentKeepaliveKey = "kilo.squat.ai/persistent-keepalive"
  55. wireGuardIPAnnotationKey = "kilo.squat.ai/wireguard-ip"
  56. discoveredEndpointsKey = "kilo.squat.ai/discovered-endpoints"
  57. allowedLocationIPsKey = "kilo.squat.ai/allowed-location-ips"
  58. // RegionLabelKey is the key for the well-known Kubernetes topology region label.
  59. RegionLabelKey = "topology.kubernetes.io/region"
  60. jsonPatchSlash = "~1"
  61. jsonRemovePatch = `{"op": "remove", "path": "%s"}`
  62. )
  63. type backend struct {
  64. nodes *nodeBackend
  65. peers *peerBackend
  66. }
  67. // Nodes implements the mesh.Backend interface.
  68. func (b *backend) Nodes() mesh.NodeBackend {
  69. return b.nodes
  70. }
  71. // Peers implements the mesh.Backend interface.
  72. func (b *backend) Peers() mesh.PeerBackend {
  73. return b.peers
  74. }
  75. type nodeBackend struct {
  76. client kubernetes.Interface
  77. events chan *mesh.NodeEvent
  78. informer cache.SharedIndexInformer
  79. lister v1listers.NodeLister
  80. topologyLabel string
  81. }
  82. type peerBackend struct {
  83. client kiloclient.Interface
  84. extensionsClient apiextensions.Interface
  85. events chan *mesh.PeerEvent
  86. informer cache.SharedIndexInformer
  87. lister v1alpha1listers.PeerLister
  88. }
  89. // New creates a new instance of a mesh.Backend.
  90. func New(c kubernetes.Interface, kc kiloclient.Interface, ec apiextensions.Interface, topologyLabel string) mesh.Backend {
  91. ni := v1informers.NewNodeInformer(c, 5*time.Minute, nil)
  92. pi := v1alpha1informers.NewPeerInformer(kc, 5*time.Minute, nil)
  93. return &backend{
  94. &nodeBackend{
  95. client: c,
  96. events: make(chan *mesh.NodeEvent),
  97. informer: ni,
  98. lister: v1listers.NewNodeLister(ni.GetIndexer()),
  99. topologyLabel: topologyLabel,
  100. },
  101. &peerBackend{
  102. client: kc,
  103. extensionsClient: ec,
  104. events: make(chan *mesh.PeerEvent),
  105. informer: pi,
  106. lister: v1alpha1listers.NewPeerLister(pi.GetIndexer()),
  107. },
  108. }
  109. }
  110. // CleanUp removes configuration applied to the backend.
  111. func (nb *nodeBackend) CleanUp(name string) error {
  112. patch := []byte("[" + strings.Join([]string{
  113. fmt.Sprintf(jsonRemovePatch, path.Join("/metadata", "annotations", strings.Replace(endpointAnnotationKey, "/", jsonPatchSlash, 1))),
  114. fmt.Sprintf(jsonRemovePatch, path.Join("/metadata", "annotations", strings.Replace(internalIPAnnotationKey, "/", jsonPatchSlash, 1))),
  115. fmt.Sprintf(jsonRemovePatch, path.Join("/metadata", "annotations", strings.Replace(keyAnnotationKey, "/", jsonPatchSlash, 1))),
  116. fmt.Sprintf(jsonRemovePatch, path.Join("/metadata", "annotations", strings.Replace(lastSeenAnnotationKey, "/", jsonPatchSlash, 1))),
  117. fmt.Sprintf(jsonRemovePatch, path.Join("/metadata", "annotations", strings.Replace(wireGuardIPAnnotationKey, "/", jsonPatchSlash, 1))),
  118. fmt.Sprintf(jsonRemovePatch, path.Join("/metadata", "annotations", strings.Replace(discoveredEndpointsKey, "/", jsonPatchSlash, 1))),
  119. }, ",") + "]")
  120. if _, err := nb.client.CoreV1().Nodes().Patch(context.TODO(), name, types.JSONPatchType, patch, metav1.PatchOptions{}); err != nil {
  121. return fmt.Errorf("failed to patch node: %v", err)
  122. }
  123. return nil
  124. }
  125. // Get gets a single Node by name.
  126. func (nb *nodeBackend) Get(name string) (*mesh.Node, error) {
  127. n, err := nb.lister.Get(name)
  128. if err != nil {
  129. return nil, err
  130. }
  131. return translateNode(n, nb.topologyLabel), nil
  132. }
  133. // Init initializes the backend; for this backend that means
  134. // syncing the informer cache.
  135. func (nb *nodeBackend) Init(stop <-chan struct{}) error {
  136. go nb.informer.Run(stop)
  137. if ok := cache.WaitForCacheSync(stop, func() bool {
  138. return nb.informer.HasSynced()
  139. }); !ok {
  140. return errors.New("failed to sync node cache")
  141. }
  142. nb.informer.AddEventHandler(
  143. cache.ResourceEventHandlerFuncs{
  144. AddFunc: func(obj interface{}) {
  145. n, ok := obj.(*v1.Node)
  146. if !ok {
  147. // Failed to decode Node; ignoring...
  148. return
  149. }
  150. nb.events <- &mesh.NodeEvent{Type: mesh.AddEvent, Node: translateNode(n, nb.topologyLabel)}
  151. },
  152. UpdateFunc: func(old, obj interface{}) {
  153. n, ok := obj.(*v1.Node)
  154. if !ok {
  155. // Failed to decode Node; ignoring...
  156. return
  157. }
  158. o, ok := old.(*v1.Node)
  159. if !ok {
  160. // Failed to decode Node; ignoring...
  161. return
  162. }
  163. nb.events <- &mesh.NodeEvent{Type: mesh.UpdateEvent, Node: translateNode(n, nb.topologyLabel), Old: translateNode(o, nb.topologyLabel)}
  164. },
  165. DeleteFunc: func(obj interface{}) {
  166. n, ok := obj.(*v1.Node)
  167. if !ok {
  168. // Failed to decode Node; ignoring...
  169. return
  170. }
  171. nb.events <- &mesh.NodeEvent{Type: mesh.DeleteEvent, Node: translateNode(n, nb.topologyLabel)}
  172. },
  173. },
  174. )
  175. return nil
  176. }
  177. // List gets all the Nodes in the cluster.
  178. func (nb *nodeBackend) List() ([]*mesh.Node, error) {
  179. ns, err := nb.lister.List(labels.Everything())
  180. if err != nil {
  181. return nil, err
  182. }
  183. nodes := make([]*mesh.Node, len(ns))
  184. for i := range ns {
  185. nodes[i] = translateNode(ns[i], nb.topologyLabel)
  186. }
  187. return nodes, nil
  188. }
  189. // Set sets the fields of a node.
  190. func (nb *nodeBackend) Set(name string, node *mesh.Node) error {
  191. old, err := nb.lister.Get(name)
  192. if err != nil {
  193. return fmt.Errorf("failed to find node: %v", err)
  194. }
  195. n := old.DeepCopy()
  196. n.ObjectMeta.Annotations[endpointAnnotationKey] = node.Endpoint.String()
  197. if node.InternalIP == nil {
  198. n.ObjectMeta.Annotations[internalIPAnnotationKey] = ""
  199. } else {
  200. n.ObjectMeta.Annotations[internalIPAnnotationKey] = node.InternalIP.String()
  201. }
  202. n.ObjectMeta.Annotations[keyAnnotationKey] = string(node.Key)
  203. n.ObjectMeta.Annotations[lastSeenAnnotationKey] = strconv.FormatInt(node.LastSeen, 10)
  204. if node.WireGuardIP == nil {
  205. n.ObjectMeta.Annotations[wireGuardIPAnnotationKey] = ""
  206. } else {
  207. n.ObjectMeta.Annotations[wireGuardIPAnnotationKey] = node.WireGuardIP.String()
  208. }
  209. if node.DiscoveredEndpoints == nil {
  210. n.ObjectMeta.Annotations[discoveredEndpointsKey] = ""
  211. } else {
  212. discoveredEndpoints, err := json.Marshal(node.DiscoveredEndpoints)
  213. if err != nil {
  214. return err
  215. }
  216. n.ObjectMeta.Annotations[discoveredEndpointsKey] = string(discoveredEndpoints)
  217. }
  218. oldData, err := json.Marshal(old)
  219. if err != nil {
  220. return err
  221. }
  222. newData, err := json.Marshal(n)
  223. if err != nil {
  224. return err
  225. }
  226. patch, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, v1.Node{})
  227. if err != nil {
  228. return fmt.Errorf("failed to create patch for node %q: %v", n.Name, err)
  229. }
  230. if _, err = nb.client.CoreV1().Nodes().Patch(context.TODO(), name, types.StrategicMergePatchType, patch, metav1.PatchOptions{}); err != nil {
  231. return fmt.Errorf("failed to patch node: %v", err)
  232. }
  233. return nil
  234. }
  235. // Watch returns a chan of node events.
  236. func (nb *nodeBackend) Watch() <-chan *mesh.NodeEvent {
  237. return nb.events
  238. }
  239. // translateNode translates a Kubernetes Node to a mesh.Node.
  240. func translateNode(node *v1.Node, topologyLabel string) *mesh.Node {
  241. if node == nil {
  242. return nil
  243. }
  244. _, subnet, err := net.ParseCIDR(node.Spec.PodCIDR)
  245. // The subnet should only ever fail to parse if the pod CIDR has not been set,
  246. // so in this case set the subnet to nil and let the node be updated.
  247. if err != nil {
  248. subnet = nil
  249. }
  250. _, leader := node.ObjectMeta.Annotations[leaderAnnotationKey]
  251. // Allow the region to be overridden by an explicit location.
  252. location, ok := node.ObjectMeta.Annotations[locationAnnotationKey]
  253. if !ok {
  254. location = node.ObjectMeta.Labels[topologyLabel]
  255. }
  256. // Allow the endpoint to be overridden.
  257. endpoint := parseEndpoint(node.ObjectMeta.Annotations[forceEndpointAnnotationKey])
  258. if endpoint == nil {
  259. endpoint = parseEndpoint(node.ObjectMeta.Annotations[endpointAnnotationKey])
  260. }
  261. // Allow the internal IP to be overridden.
  262. internalIP := normalizeIP(node.ObjectMeta.Annotations[forceInternalIPAnnotationKey])
  263. if internalIP == nil {
  264. internalIP = normalizeIP(node.ObjectMeta.Annotations[internalIPAnnotationKey])
  265. }
  266. // Set the ForceInternalIP flag, if force-internal-ip annotation was set to "".
  267. noInternalIP := false
  268. if s, ok := node.ObjectMeta.Annotations[forceInternalIPAnnotationKey]; ok && (s == "" || s == "-") {
  269. noInternalIP = true
  270. internalIP = nil
  271. }
  272. // Set Wireguard PersistentKeepalive setting for the node.
  273. var persistentKeepalive int64
  274. if keepAlive, ok := node.ObjectMeta.Annotations[persistentKeepaliveKey]; !ok {
  275. persistentKeepalive = 0
  276. } else {
  277. if persistentKeepalive, err = strconv.ParseInt(keepAlive, 10, 64); err != nil {
  278. persistentKeepalive = 0
  279. }
  280. }
  281. var lastSeen int64
  282. if ls, ok := node.ObjectMeta.Annotations[lastSeenAnnotationKey]; !ok {
  283. lastSeen = 0
  284. } else {
  285. if lastSeen, err = strconv.ParseInt(ls, 10, 64); err != nil {
  286. lastSeen = 0
  287. }
  288. }
  289. var discoveredEndpoints map[string]*wireguard.Endpoint
  290. if de, ok := node.ObjectMeta.Annotations[discoveredEndpointsKey]; ok {
  291. err := json.Unmarshal([]byte(de), &discoveredEndpoints)
  292. if err != nil {
  293. discoveredEndpoints = nil
  294. }
  295. }
  296. // Set allowed IPs for a location.
  297. var allowedLocationIPs []*net.IPNet
  298. if str, ok := node.ObjectMeta.Annotations[allowedLocationIPsKey]; ok {
  299. for _, ip := range strings.Split(str, ",") {
  300. if ipnet := normalizeIP(ip); ipnet != nil {
  301. allowedLocationIPs = append(allowedLocationIPs, ipnet)
  302. }
  303. }
  304. }
  305. return &mesh.Node{
  306. // Endpoint and InternalIP should only ever fail to parse if the
  307. // remote node's agent has not yet set its IP address;
  308. // in this case the IP will be nil and
  309. // the mesh can wait for the node to be updated.
  310. // It is valid for the InternalIP to be nil,
  311. // if the given node only has public IP addresses.
  312. Endpoint: endpoint,
  313. NoInternalIP: noInternalIP,
  314. InternalIP: internalIP,
  315. Key: []byte(node.ObjectMeta.Annotations[keyAnnotationKey]),
  316. LastSeen: lastSeen,
  317. Leader: leader,
  318. Location: location,
  319. Name: node.Name,
  320. PersistentKeepalive: int(persistentKeepalive),
  321. Subnet: subnet,
  322. // WireGuardIP can fail to parse if the node is not a leader or if
  323. // the node's agent has not yet reconciled. In either case, the IP
  324. // will parse as nil.
  325. WireGuardIP: normalizeIP(node.ObjectMeta.Annotations[wireGuardIPAnnotationKey]),
  326. DiscoveredEndpoints: discoveredEndpoints,
  327. AllowedLocationIPs: allowedLocationIPs,
  328. }
  329. }
  330. // translatePeer translates a Peer CRD to a mesh.Peer.
  331. func translatePeer(peer *v1alpha1.Peer) *mesh.Peer {
  332. if peer == nil {
  333. return nil
  334. }
  335. var aips []*net.IPNet
  336. for _, aip := range peer.Spec.AllowedIPs {
  337. aip := normalizeIP(aip)
  338. // Skip any invalid IPs.
  339. if aip == nil {
  340. continue
  341. }
  342. aips = append(aips, aip)
  343. }
  344. var endpoint *wireguard.Endpoint
  345. if peer.Spec.Endpoint != nil {
  346. ip := net.ParseIP(peer.Spec.Endpoint.IP)
  347. if ip4 := ip.To4(); ip4 != nil {
  348. ip = ip4
  349. } else {
  350. ip = ip.To16()
  351. }
  352. if peer.Spec.Endpoint.Port > 0 && (ip != nil || peer.Spec.Endpoint.DNS != "") {
  353. endpoint = &wireguard.Endpoint{
  354. DNSOrIP: wireguard.DNSOrIP{
  355. DNS: peer.Spec.Endpoint.DNS,
  356. IP: ip,
  357. },
  358. Port: peer.Spec.Endpoint.Port,
  359. }
  360. }
  361. }
  362. var key []byte
  363. if len(peer.Spec.PublicKey) > 0 {
  364. key = []byte(peer.Spec.PublicKey)
  365. }
  366. var psk []byte
  367. if len(peer.Spec.PresharedKey) > 0 {
  368. psk = []byte(peer.Spec.PresharedKey)
  369. }
  370. var pka int
  371. if peer.Spec.PersistentKeepalive > 0 {
  372. pka = peer.Spec.PersistentKeepalive
  373. }
  374. return &mesh.Peer{
  375. Name: peer.Name,
  376. Peer: wireguard.Peer{
  377. AllowedIPs: aips,
  378. Endpoint: endpoint,
  379. PersistentKeepalive: pka,
  380. PresharedKey: psk,
  381. PublicKey: key,
  382. },
  383. }
  384. }
  385. // CleanUp removes configuration applied to the backend.
  386. func (pb *peerBackend) CleanUp(name string) error {
  387. return nil
  388. }
  389. // Get gets a single Peer by name.
  390. func (pb *peerBackend) Get(name string) (*mesh.Peer, error) {
  391. p, err := pb.lister.Get(name)
  392. if err != nil {
  393. return nil, err
  394. }
  395. return translatePeer(p), nil
  396. }
  397. // Init initializes the backend; for this backend that means
  398. // syncing the informer cache.
  399. func (pb *peerBackend) Init(stop <-chan struct{}) error {
  400. // Check the presents of the CRD peers.kilo.squat.ai.
  401. if _, err := pb.extensionsClient.ApiextensionsV1().CustomResourceDefinitions().Get(context.TODO(), strings.Join([]string{v1alpha1.PeerPlural, v1alpha1.GroupName}, "."), metav1.GetOptions{}); err != nil {
  402. return fmt.Errorf("CRD is not present: %v", err)
  403. }
  404. go pb.informer.Run(stop)
  405. if ok := cache.WaitForCacheSync(stop, func() bool {
  406. return pb.informer.HasSynced()
  407. }); !ok {
  408. return errors.New("failed to sync peer cache")
  409. }
  410. pb.informer.AddEventHandler(
  411. cache.ResourceEventHandlerFuncs{
  412. AddFunc: func(obj interface{}) {
  413. p, ok := obj.(*v1alpha1.Peer)
  414. if !ok || p.Validate() != nil {
  415. // Failed to decode Peer; ignoring...
  416. return
  417. }
  418. pb.events <- &mesh.PeerEvent{Type: mesh.AddEvent, Peer: translatePeer(p)}
  419. },
  420. UpdateFunc: func(old, obj interface{}) {
  421. p, ok := obj.(*v1alpha1.Peer)
  422. if !ok || p.Validate() != nil {
  423. // Failed to decode Peer; ignoring...
  424. return
  425. }
  426. o, ok := old.(*v1alpha1.Peer)
  427. if !ok || o.Validate() != nil {
  428. // Failed to decode Peer; ignoring...
  429. return
  430. }
  431. pb.events <- &mesh.PeerEvent{Type: mesh.UpdateEvent, Peer: translatePeer(p), Old: translatePeer(o)}
  432. },
  433. DeleteFunc: func(obj interface{}) {
  434. p, ok := obj.(*v1alpha1.Peer)
  435. if !ok || p.Validate() != nil {
  436. // Failed to decode Peer; ignoring...
  437. return
  438. }
  439. pb.events <- &mesh.PeerEvent{Type: mesh.DeleteEvent, Peer: translatePeer(p)}
  440. },
  441. },
  442. )
  443. return nil
  444. }
  445. // List gets all the Peers in the cluster.
  446. func (pb *peerBackend) List() ([]*mesh.Peer, error) {
  447. ps, err := pb.lister.List(labels.Everything())
  448. if err != nil {
  449. return nil, err
  450. }
  451. peers := make([]*mesh.Peer, len(ps))
  452. for i := range ps {
  453. // Skip invalid peers.
  454. if ps[i].Validate() != nil {
  455. continue
  456. }
  457. peers[i] = translatePeer(ps[i])
  458. }
  459. return peers, nil
  460. }
  461. // Set sets the fields of a peer.
  462. func (pb *peerBackend) Set(name string, peer *mesh.Peer) error {
  463. old, err := pb.lister.Get(name)
  464. if err != nil {
  465. return fmt.Errorf("failed to find peer: %v", err)
  466. }
  467. p := old.DeepCopy()
  468. p.Spec.AllowedIPs = make([]string, len(peer.AllowedIPs))
  469. for i := range peer.AllowedIPs {
  470. p.Spec.AllowedIPs[i] = peer.AllowedIPs[i].String()
  471. }
  472. if peer.Endpoint != nil {
  473. var ip string
  474. if peer.Endpoint.IP != nil {
  475. ip = peer.Endpoint.IP.String()
  476. }
  477. p.Spec.Endpoint = &v1alpha1.PeerEndpoint{
  478. DNSOrIP: v1alpha1.DNSOrIP{
  479. IP: ip,
  480. DNS: peer.Endpoint.DNS,
  481. },
  482. Port: peer.Endpoint.Port,
  483. }
  484. }
  485. p.Spec.PersistentKeepalive = peer.PersistentKeepalive
  486. p.Spec.PresharedKey = string(peer.PresharedKey)
  487. p.Spec.PublicKey = string(peer.PublicKey)
  488. if _, err = pb.client.KiloV1alpha1().Peers().Update(context.TODO(), p, metav1.UpdateOptions{}); err != nil {
  489. return fmt.Errorf("failed to update peer: %v", err)
  490. }
  491. return nil
  492. }
  493. // Watch returns a chan of peer events.
  494. func (pb *peerBackend) Watch() <-chan *mesh.PeerEvent {
  495. return pb.events
  496. }
  497. func normalizeIP(ip string) *net.IPNet {
  498. i, ipNet, err := net.ParseCIDR(ip)
  499. if err != nil || ipNet == nil {
  500. return nil
  501. }
  502. if ip4 := i.To4(); ip4 != nil {
  503. ipNet.IP = ip4
  504. return ipNet
  505. }
  506. ipNet.IP = i.To16()
  507. return ipNet
  508. }
  509. func parseEndpoint(endpoint string) *wireguard.Endpoint {
  510. if len(endpoint) == 0 {
  511. return nil
  512. }
  513. parts := strings.Split(endpoint, ":")
  514. if len(parts) < 2 {
  515. return nil
  516. }
  517. portRaw := parts[len(parts)-1]
  518. hostRaw := strings.Trim(strings.Join(parts[:len(parts)-1], ":"), "[]")
  519. port, err := strconv.ParseUint(portRaw, 10, 32)
  520. if err != nil {
  521. return nil
  522. }
  523. if len(validation.IsValidPortNum(int(port))) != 0 {
  524. return nil
  525. }
  526. ip := net.ParseIP(hostRaw)
  527. if ip == nil {
  528. if len(validation.IsDNS1123Subdomain(hostRaw)) == 0 {
  529. return &wireguard.Endpoint{DNSOrIP: wireguard.DNSOrIP{DNS: hostRaw}, Port: uint32(port)}
  530. }
  531. return nil
  532. }
  533. if ip4 := ip.To4(); ip4 != nil {
  534. ip = ip4
  535. } else {
  536. ip = ip.To16()
  537. }
  538. return &wireguard.Endpoint{DNSOrIP: wireguard.DNSOrIP{IP: ip}, Port: uint32(port)}
  539. }