backend.go 18 KB

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