2023-10-05 18:48:54 +02:00
|
|
|
package ip
|
2023-09-28 17:55:37 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/sha1"
|
2023-10-25 19:34:38 +02:00
|
|
|
"fmt"
|
2023-10-05 18:48:54 +02:00
|
|
|
"net"
|
2023-09-28 17:55:37 +02:00
|
|
|
|
|
|
|
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
|
|
|
)
|
|
|
|
|
2023-10-05 18:48:54 +02:00
|
|
|
type ULABuilder struct{}
|
2023-09-28 17:55:37 +02:00
|
|
|
|
2023-10-25 19:34:38 +02:00
|
|
|
func getMeshPrefix(meshId string) [16]byte {
|
|
|
|
var ulaPrefix [16]byte
|
2023-09-28 17:55:37 +02:00
|
|
|
|
|
|
|
ulaPrefix[0] = 0xfd
|
|
|
|
|
|
|
|
s := sha1.Sum([]byte(meshId))
|
|
|
|
|
|
|
|
for i := 1; i < 7; i++ {
|
|
|
|
ulaPrefix[i] = s[i-1]
|
|
|
|
}
|
|
|
|
|
|
|
|
ulaPrefix[7] = 1
|
|
|
|
return ulaPrefix
|
|
|
|
}
|
|
|
|
|
2023-10-25 19:34:38 +02:00
|
|
|
func (u *ULABuilder) GetIPNet(meshId string) (*net.IPNet, error) {
|
|
|
|
meshBytes := getMeshPrefix(meshId)
|
|
|
|
var meshIP net.IP = meshBytes[:]
|
|
|
|
|
|
|
|
ip := fmt.Sprintf("%s/%d", meshIP.String(), 64)
|
|
|
|
_, net, err := net.ParseCIDR(ip)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return net, nil
|
|
|
|
}
|
|
|
|
|
2023-10-05 18:48:54 +02:00
|
|
|
func (u *ULABuilder) GetIP(key wgtypes.Key, meshId string) (net.IP, error) {
|
2023-10-25 19:34:38 +02:00
|
|
|
ulaPrefix := getMeshPrefix(meshId)
|
2023-09-28 17:55:37 +02:00
|
|
|
|
2023-10-05 18:48:54 +02:00
|
|
|
c, err := NewCga(key, ulaPrefix)
|
2023-09-28 17:55:37 +02:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2023-10-05 18:48:54 +02:00
|
|
|
return c.GetIP(), nil
|
2023-09-28 17:55:37 +02:00
|
|
|
}
|