util

package
v0.27.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 11, 2025 License: BSD-3-Clause Imports: 34 Imported by: 1

Documentation

Index

Constants

View Source
const (
	RegisterMethodAuthKey = "authkey"
	RegisterMethodOIDC    = "oidc"
	RegisterMethodCLI     = "cli"
)
View Source
const (
	ByteSize = 8

	// value related to RFC 1123 and 952.
	LabelHostnameLength = 63
)
View Source
const (
	Base8              = 8
	Base10             = 10
	BitSize16          = 16
	BitSize32          = 32
	BitSize64          = 64
	PermissionFallback = 0o700
)

Variables

View Source
var (
	ErrCannotDecryptResponse = errors.New("cannot decrypt response")
	ZstdCompression          = "zstd"
)
View Source
var AddrPortComparer = cmp.Comparer(func(x, y netip.AddrPort) bool {
	return x == y
})
View Source
var DkeyComparer = cmp.Comparer(func(x, y key.DiscoPublic) bool {
	return x.String() == y.String()
})
View Source
var ErrInvalidHostName = errors.New("invalid hostname")
View Source
var IPComparer = cmp.Comparer(func(x, y netip.Addr) bool {
	return x.Compare(y) == 0
})
View Source
var MkeyComparer = cmp.Comparer(func(x, y key.MachinePublic) bool {
	return x.String() == y.String()
})
View Source
var NkeyComparer = cmp.Comparer(func(x, y key.NodePublic) bool {
	return x.String() == y.String()
})
View Source
var PrefixComparer = cmp.Comparer(func(x, y netip.Prefix) bool {
	return x == y
})
View Source
var TheInternet = sync.OnceValue(func() *netipx.IPSet {
	var internetBuilder netipx.IPSetBuilder
	internetBuilder.AddPrefix(netip.MustParsePrefix("2000::/3"))
	internetBuilder.AddPrefix(tsaddr.AllIPv4())

	internetBuilder.RemovePrefix(netip.MustParsePrefix("fc00::/7"))
	internetBuilder.RemovePrefix(netip.MustParsePrefix("10.0.0.0/8"))
	internetBuilder.RemovePrefix(netip.MustParsePrefix("172.16.0.0/12"))
	internetBuilder.RemovePrefix(netip.MustParsePrefix("192.168.0.0/16"))

	internetBuilder.RemovePrefix(tsaddr.TailscaleULARange())
	internetBuilder.RemovePrefix(tsaddr.CGNATRange())

	internetBuilder.RemovePrefix(netip.MustParsePrefix("fe80::/10"))
	internetBuilder.RemovePrefix(netip.MustParsePrefix("169.254.0.0/16"))

	theInternetSet, _ := internetBuilder.IPSet()

	return theInternetSet
})

TheInternet returns the IPSet for the Internet. https://www.youtube.com/watch?v=iDbyYGrswtg

View Source
var ViewSliceIPProtoComparer = cmp.Comparer(func(a, b views.Slice[ipproto.Proto]) bool { return views.SliceEqual(a, b) })

Functions

func AbsolutePathFromConfigPath

func AbsolutePathFromConfigPath(path string) string

func EnsureDir

func EnsureDir(dir string) error

func EnsureHostname added in v0.27.0

func EnsureHostname(hostinfo *tailcfg.Hostinfo, machineKey, nodeKey string) string

SafeHostname extracts a hostname from Hostinfo, providing sensible defaults if Hostinfo is nil or Hostname is empty. This prevents nil pointer dereferences and ensures nodes always have a valid hostname. The hostname is truncated to 63 characters to comply with DNS label length limits (RFC 1123). EnsureHostname guarantees a valid hostname for node registration. This function never fails - it always returns a valid hostname.

Strategy: 1. If hostinfo is nil/empty → generate default from keys 2. If hostname is provided → normalise it 3. If normalisation fails → generate invalid-<random> replacement

Returns the guaranteed-valid hostname to use.

func GenerateIPv4DNSRootDomain

func GenerateIPv4DNSRootDomain(ipPrefix netip.Prefix) []dnsname.FQDN

From the netmask we can find out the wildcard bits (the bits that are not set in the netmask). This allows us to then calculate the subnets included in the subsequent class block and generate the entries.

func GenerateIPv6DNSRootDomain

func GenerateIPv6DNSRootDomain(ipPrefix netip.Prefix) []dnsname.FQDN

From the netmask we can find out the wildcard bits (the bits that are not set in the netmask). This allows us to then calculate the subnets included in the subsequent class block and generate the entries.

func GenerateRandomBytes

func GenerateRandomBytes(n int) ([]byte, error)

GenerateRandomBytes returns securely generated random bytes. It will return an error if the system's secure random number generator fails to function correctly, in which case the caller should not continue.

func GenerateRandomStringDNSSafe

func GenerateRandomStringDNSSafe(size int) (string, error)

GenerateRandomStringDNSSafe returns a DNS-safe securely generated random string. It will return an error if the system's secure random number generator fails to function correctly, in which case the caller should not continue.

func GenerateRandomStringURLSafe

func GenerateRandomStringURLSafe(n int) (string, error)

GenerateRandomStringURLSafe returns a URL-safe, base64 encoded securely generated random string. It will return an error if the system's secure random number generator fails to function correctly, in which case the caller should not continue.

func GetFileMode

func GetFileMode(key string) fs.FileMode

func GetIPPrefixEndpoints

func GetIPPrefixEndpoints(na netip.Prefix) (netip.Addr, netip.Addr)

func GrpcSocketDialer

func GrpcSocketDialer(ctx context.Context, addr string) (net.Conn, error)

func IPSetAddrIter added in v0.26.0

func IPSetAddrIter(ipSet *netipx.IPSet) iter.Seq[netip.Addr]

IPSetAddrIter returns a function that iterates over all the IPs in the IPSet.

func InvalidString added in v0.27.0

func InvalidString() string

func IsCI added in v0.26.0

func IsCI() bool

func LogErr

func LogErr(err error, msg string)

func MustGenerateRandomStringDNSSafe added in v0.26.0

func MustGenerateRandomStringDNSSafe(size int) string

func MustStringsToPrefixes added in v0.26.0

func MustStringsToPrefixes(strings []string) []netip.Prefix

func NormaliseHostname added in v0.27.0

func NormaliseHostname(name string) (string, error)

NormaliseHostname transforms a string into a valid DNS hostname. Returns error if the transformation results in an invalid hostname.

Transformations applied: - Converts to lowercase - Removes invalid DNS characters - Truncates to 63 characters if needed

After transformation, validates the result.

func ParseIPSet

func ParseIPSet(arg string, bits *int) (*netipx.IPSet, error)

parseIPSet parses arg as one:

  • an IP address (IPv4 or IPv6)
  • the string "*" to match everything (both IPv4 & IPv6)
  • a CIDR (e.g. "192.168.0.0/16")
  • a range of two IPs, inclusive, separated by hyphen ("2eff::1-2eff::0800")

bits, if non-nil, is the legacy SrcBits CIDR length to make a IP address (without a slash) treated as a CIDR of *bits length. nolint

func ParseLoginURLFromCLILogin added in v0.25.1

func ParseLoginURLFromCLILogin(output string) (*url.URL, error)

ParseLoginURLFromCLILogin parses the output of the tailscale up command to extract the login URL. It returns an error if not exactly one URL is found.

func PrefixesToString added in v0.26.0

func PrefixesToString(prefixes []netip.Prefix) []string

func StringToIPPrefix

func StringToIPPrefix(prefixes []string) ([]netip.Prefix, error)

func TSLogfWrapper

func TSLogfWrapper() logger.Logf

func TailMapResponseToString

func TailMapResponseToString(resp tailcfg.MapResponse) string

func TailNodesToString

func TailNodesToString(nodes []*tailcfg.Node) string

func TailcfgFilterRulesToString added in v0.26.0

func TailcfgFilterRulesToString(rules []tailcfg.FilterRule) string

func TailscaleVersionNewerOrEqual

func TailscaleVersionNewerOrEqual(minimum, toCheck string) bool

func ValidateHostname added in v0.27.0

func ValidateHostname(name string) error

ValidateHostname checks if a hostname meets DNS requirements. This function does NOT modify the input - it only validates. The hostname must already be lowercase and contain only valid characters.

func ValidateUsername added in v0.24.0

func ValidateUsername(username string) error

ValidateUsername checks if a username is valid. It must be at least 2 characters long, start with a letter, and contain only letters, numbers, hyphens, dots, and underscores. It cannot contain more than one '@'. It cannot contain invalid characters.

func YesNo added in v0.27.0

func YesNo(msg string) bool

YesNo takes a question and prompts the user to answer the question with a yes or no. It appends a y/n to the message. The question is written to stderr so that content can be redirected without interfering with the prompt.

Types

type DBLogWrapper

type DBLogWrapper struct {
	Logger                *zerolog.Logger
	Level                 zerolog.Level
	Event                 *zerolog.Event
	SlowThreshold         time.Duration
	SkipErrRecordNotFound bool
	ParameterizedQueries  bool
}

func NewDBLogWrapper

func NewDBLogWrapper(origin *zerolog.Logger, slowThreshold time.Duration, skipErrRecordNotFound bool, parameterizedQueries bool) *DBLogWrapper

func (*DBLogWrapper) Error

func (l *DBLogWrapper) Error(ctx context.Context, msg string, data ...interface{})

func (*DBLogWrapper) Info

func (l *DBLogWrapper) Info(ctx context.Context, msg string, data ...interface{})

func (*DBLogWrapper) LogMode

func (*DBLogWrapper) ParamsFilter

func (l *DBLogWrapper) ParamsFilter(ctx context.Context, sql string, params ...interface{}) (string, []interface{})

func (*DBLogWrapper) Trace

func (l *DBLogWrapper) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error)

func (*DBLogWrapper) Warn

func (l *DBLogWrapper) Warn(ctx context.Context, msg string, data ...interface{})

type DBLogWrapperOption

type DBLogWrapperOption func(*DBLogWrapper)

type Traceroute added in v0.26.0

type Traceroute struct {
	// Hostname is the resolved hostname or IP address identifying the target
	Hostname string

	// IP is the IP address of the target
	IP netip.Addr

	// Route is the path taken to reach the target if successful. The list is ordered by the path taken.
	Route []TraceroutePath

	// Success indicates if the traceroute was successful.
	Success bool

	// Err contains an error if  the traceroute was not successful.
	Err error
}

func ParseTraceroute added in v0.26.0

func ParseTraceroute(output string) (Traceroute, error)

ParseTraceroute parses the output of the traceroute command and returns a Traceroute struct.

type TraceroutePath added in v0.26.0

type TraceroutePath struct {
	// Hop is the current jump in the total traceroute.
	Hop int

	// Hostname is the resolved hostname or IP address identifying the jump
	Hostname string

	// IP is the IP address of the jump
	IP netip.Addr

	// Latencies is a list of the latencies for this jump
	Latencies []time.Duration
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL