backend.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "net"
  20. "path"
  21. "strconv"
  22. "strings"
  23. "time"
  24. crdutils "github.com/ant31/crd-validation/pkg"
  25. v1 "k8s.io/api/core/v1"
  26. "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
  27. apiextensions "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
  28. apierrors "k8s.io/apimachinery/pkg/api/errors"
  29. "k8s.io/apimachinery/pkg/labels"
  30. "k8s.io/apimachinery/pkg/types"
  31. "k8s.io/apimachinery/pkg/util/strategicpatch"
  32. "k8s.io/apimachinery/pkg/util/validation"
  33. v1informers "k8s.io/client-go/informers/core/v1"
  34. "k8s.io/client-go/kubernetes"
  35. v1listers "k8s.io/client-go/listers/core/v1"
  36. "k8s.io/client-go/tools/cache"
  37. "github.com/squat/kilo/pkg/k8s/apis/kilo/v1alpha1"
  38. kiloclient "github.com/squat/kilo/pkg/k8s/clientset/versioned"
  39. v1alpha1informers "github.com/squat/kilo/pkg/k8s/informers/kilo/v1alpha1"
  40. v1alpha1listers "github.com/squat/kilo/pkg/k8s/listers/kilo/v1alpha1"
  41. "github.com/squat/kilo/pkg/mesh"
  42. "github.com/squat/kilo/pkg/wireguard"
  43. )
  44. const (
  45. // Backend is the name of this mesh backend.
  46. Backend = "kubernetes"
  47. endpointAnnotationKey = "kilo.squat.ai/endpoint"
  48. forceEndpointAnnotationKey = "kilo.squat.ai/force-endpoint"
  49. forceInternalIPAnnotationKey = "kilo.squat.ai/force-internal-ip"
  50. internalIPAnnotationKey = "kilo.squat.ai/internal-ip"
  51. keyAnnotationKey = "kilo.squat.ai/key"
  52. lastSeenAnnotationKey = "kilo.squat.ai/last-seen"
  53. leaderAnnotationKey = "kilo.squat.ai/leader"
  54. locationAnnotationKey = "kilo.squat.ai/location"
  55. persistentKeepaliveKey = "kilo.squat.ai/persistent-keepalive"
  56. wireGuardIPAnnotationKey = "kilo.squat.ai/wireguard-ip"
  57. discoveredEndpointsKey = "kilo.squat.ai/discovered-endpoints"
  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(name, types.JSONPatchType, patch); 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(name, types.StrategicMergePatchType, patch); 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. return &mesh.Node{
  297. // Endpoint and InternalIP should only ever fail to parse if the
  298. // remote node's agent has not yet set its IP address;
  299. // in this case the IP will be nil and
  300. // the mesh can wait for the node to be updated.
  301. // It is valid for the InternalIP to be nil,
  302. // if the given node only has public IP addresses.
  303. Endpoint: endpoint,
  304. NoInternalIP: noInternalIP,
  305. InternalIP: internalIP,
  306. Key: []byte(node.ObjectMeta.Annotations[keyAnnotationKey]),
  307. LastSeen: lastSeen,
  308. Leader: leader,
  309. Location: location,
  310. Name: node.Name,
  311. PersistentKeepalive: int(persistentKeepalive),
  312. Subnet: subnet,
  313. // WireGuardIP can fail to parse if the node is not a leader or if
  314. // the node's agent has not yet reconciled. In either case, the IP
  315. // will parse as nil.
  316. WireGuardIP: normalizeIP(node.ObjectMeta.Annotations[wireGuardIPAnnotationKey]),
  317. DiscoveredEndpoints: discoveredEndpoints,
  318. }
  319. }
  320. // translatePeer translates a Peer CRD to a mesh.Peer.
  321. func translatePeer(peer *v1alpha1.Peer) *mesh.Peer {
  322. if peer == nil {
  323. return nil
  324. }
  325. var aips []*net.IPNet
  326. for _, aip := range peer.Spec.AllowedIPs {
  327. aip := normalizeIP(aip)
  328. // Skip any invalid IPs.
  329. if aip == nil {
  330. continue
  331. }
  332. aips = append(aips, aip)
  333. }
  334. var endpoint *wireguard.Endpoint
  335. if peer.Spec.Endpoint != nil {
  336. ip := net.ParseIP(peer.Spec.Endpoint.IP)
  337. if ip4 := ip.To4(); ip4 != nil {
  338. ip = ip4
  339. } else {
  340. ip = ip.To16()
  341. }
  342. if peer.Spec.Endpoint.Port > 0 && (ip != nil || peer.Spec.Endpoint.DNS != "") {
  343. endpoint = &wireguard.Endpoint{
  344. DNSOrIP: wireguard.DNSOrIP{
  345. DNS: peer.Spec.Endpoint.DNS,
  346. IP: ip,
  347. },
  348. Port: peer.Spec.Endpoint.Port,
  349. }
  350. }
  351. }
  352. var key []byte
  353. if len(peer.Spec.PublicKey) > 0 {
  354. key = []byte(peer.Spec.PublicKey)
  355. }
  356. var psk []byte
  357. if len(peer.Spec.PresharedKey) > 0 {
  358. psk = []byte(peer.Spec.PresharedKey)
  359. }
  360. var pka int
  361. if peer.Spec.PersistentKeepalive > 0 {
  362. pka = peer.Spec.PersistentKeepalive
  363. }
  364. return &mesh.Peer{
  365. Name: peer.Name,
  366. Peer: wireguard.Peer{
  367. AllowedIPs: aips,
  368. Endpoint: endpoint,
  369. PersistentKeepalive: pka,
  370. PresharedKey: psk,
  371. PublicKey: key,
  372. },
  373. }
  374. }
  375. // CleanUp removes configuration applied to the backend.
  376. func (pb *peerBackend) CleanUp(name string) error {
  377. return nil
  378. }
  379. // Get gets a single Peer by name.
  380. func (pb *peerBackend) Get(name string) (*mesh.Peer, error) {
  381. p, err := pb.lister.Get(name)
  382. if err != nil {
  383. return nil, err
  384. }
  385. return translatePeer(p), nil
  386. }
  387. // Init initializes the backend; for this backend that means
  388. // syncing the informer cache.
  389. func (pb *peerBackend) Init(stop <-chan struct{}) error {
  390. // Register CRD.
  391. crd := crdutils.NewCustomResourceDefinition(crdutils.Config{
  392. SpecDefinitionName: "github.com/squat/kilo/pkg/k8s/apis/kilo/v1alpha1.Peer",
  393. EnableValidation: true,
  394. ResourceScope: string(v1beta1.ClusterScoped),
  395. Group: v1alpha1.GroupName,
  396. Kind: v1alpha1.PeerKind,
  397. Version: v1alpha1.SchemeGroupVersion.Version,
  398. Plural: v1alpha1.PeerPlural,
  399. ShortNames: v1alpha1.PeerShortNames,
  400. GetOpenAPIDefinitions: v1alpha1.GetOpenAPIDefinitions,
  401. })
  402. crd.Spec.Subresources.Scale = nil
  403. crd.Spec.Subresources.Status = nil
  404. _, err := pb.extensionsClient.ApiextensionsV1beta1().CustomResourceDefinitions().Create(crd)
  405. if err != nil && !apierrors.IsAlreadyExists(err) {
  406. return fmt.Errorf("failed to create CRD: %v", err)
  407. }
  408. go pb.informer.Run(stop)
  409. if ok := cache.WaitForCacheSync(stop, func() bool {
  410. return pb.informer.HasSynced()
  411. }); !ok {
  412. return errors.New("failed to sync peer cache")
  413. }
  414. pb.informer.AddEventHandler(
  415. cache.ResourceEventHandlerFuncs{
  416. AddFunc: func(obj interface{}) {
  417. p, ok := obj.(*v1alpha1.Peer)
  418. if !ok || p.Validate() != nil {
  419. // Failed to decode Peer; ignoring...
  420. return
  421. }
  422. pb.events <- &mesh.PeerEvent{Type: mesh.AddEvent, Peer: translatePeer(p)}
  423. },
  424. UpdateFunc: func(old, obj interface{}) {
  425. p, ok := obj.(*v1alpha1.Peer)
  426. if !ok || p.Validate() != nil {
  427. // Failed to decode Peer; ignoring...
  428. return
  429. }
  430. o, ok := old.(*v1alpha1.Peer)
  431. if !ok || o.Validate() != nil {
  432. // Failed to decode Peer; ignoring...
  433. return
  434. }
  435. pb.events <- &mesh.PeerEvent{Type: mesh.UpdateEvent, Peer: translatePeer(p), Old: translatePeer(o)}
  436. },
  437. DeleteFunc: func(obj interface{}) {
  438. p, ok := obj.(*v1alpha1.Peer)
  439. if !ok || p.Validate() != nil {
  440. // Failed to decode Peer; ignoring...
  441. return
  442. }
  443. pb.events <- &mesh.PeerEvent{Type: mesh.DeleteEvent, Peer: translatePeer(p)}
  444. },
  445. },
  446. )
  447. return nil
  448. }
  449. // List gets all the Peers in the cluster.
  450. func (pb *peerBackend) List() ([]*mesh.Peer, error) {
  451. ps, err := pb.lister.List(labels.Everything())
  452. if err != nil {
  453. return nil, err
  454. }
  455. peers := make([]*mesh.Peer, len(ps))
  456. for i := range ps {
  457. // Skip invalid peers.
  458. if ps[i].Validate() != nil {
  459. continue
  460. }
  461. peers[i] = translatePeer(ps[i])
  462. }
  463. return peers, nil
  464. }
  465. // Set sets the fields of a peer.
  466. func (pb *peerBackend) Set(name string, peer *mesh.Peer) error {
  467. old, err := pb.lister.Get(name)
  468. if err != nil {
  469. return fmt.Errorf("failed to find peer: %v", err)
  470. }
  471. p := old.DeepCopy()
  472. p.Spec.AllowedIPs = make([]string, len(peer.AllowedIPs))
  473. for i := range peer.AllowedIPs {
  474. p.Spec.AllowedIPs[i] = peer.AllowedIPs[i].String()
  475. }
  476. if peer.Endpoint != nil {
  477. var ip string
  478. if peer.Endpoint.IP != nil {
  479. ip = peer.Endpoint.IP.String()
  480. }
  481. p.Spec.Endpoint = &v1alpha1.PeerEndpoint{
  482. DNSOrIP: v1alpha1.DNSOrIP{
  483. IP: ip,
  484. DNS: peer.Endpoint.DNS,
  485. },
  486. Port: peer.Endpoint.Port,
  487. }
  488. }
  489. p.Spec.PersistentKeepalive = peer.PersistentKeepalive
  490. p.Spec.PresharedKey = string(peer.PresharedKey)
  491. p.Spec.PublicKey = string(peer.PublicKey)
  492. if _, err = pb.client.KiloV1alpha1().Peers().Update(p); err != nil {
  493. return fmt.Errorf("failed to update peer: %v", err)
  494. }
  495. return nil
  496. }
  497. // Watch returns a chan of peer events.
  498. func (pb *peerBackend) Watch() <-chan *mesh.PeerEvent {
  499. return pb.events
  500. }
  501. func normalizeIP(ip string) *net.IPNet {
  502. i, ipNet, err := net.ParseCIDR(ip)
  503. if err != nil || ipNet == nil {
  504. return nil
  505. }
  506. if ip4 := i.To4(); ip4 != nil {
  507. ipNet.IP = ip4
  508. return ipNet
  509. }
  510. ipNet.IP = i.To16()
  511. return ipNet
  512. }
  513. func parseEndpoint(endpoint string) *wireguard.Endpoint {
  514. if len(endpoint) == 0 {
  515. return nil
  516. }
  517. parts := strings.Split(endpoint, ":")
  518. if len(parts) < 2 {
  519. return nil
  520. }
  521. portRaw := parts[len(parts)-1]
  522. hostRaw := strings.Trim(strings.Join(parts[:len(parts)-1], ":"), "[]")
  523. port, err := strconv.ParseUint(portRaw, 10, 32)
  524. if err != nil {
  525. return nil
  526. }
  527. if len(validation.IsValidPortNum(int(port))) != 0 {
  528. return nil
  529. }
  530. ip := net.ParseIP(hostRaw)
  531. if ip == nil {
  532. if len(validation.IsDNS1123Subdomain(hostRaw)) == 0 {
  533. return &wireguard.Endpoint{DNSOrIP: wireguard.DNSOrIP{DNS: hostRaw}, Port: uint32(port)}
  534. }
  535. return nil
  536. }
  537. if ip4 := ip.To4(); ip4 != nil {
  538. ip = ip4
  539. } else {
  540. ip = ip.To16()
  541. }
  542. return &wireguard.Endpoint{DNSOrIP: wireguard.DNSOrIP{IP: ip}, Port: uint32(port)}
  543. }