utils

package
v1.2.3-fred.2 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2022 License: Apache-2.0 Imports: 76 Imported by: 974

Documentation

Index

Constants

View Source
const (
	// Bold is an escape code to format as bold or increased intensity
	Bold = 1
	// Red is an escape code for red terminal color
	Red = 31
	// Yellow is an escape code for yellow terminal color
	Yellow = 33
	// Blue is an escape code for blue terminal color
	Blue = 36
	// Gray is an escape code for gray terminal color
	Gray = 37
)
View Source
const (
	// DefaultLRUCapacity is a capacity for LRU session cache
	DefaultLRUCapacity = 1024
	// DefaultCertTTL sets the TTL of the self-signed certificate (1 year)
	DefaultCertTTL = (24 * time.Hour) * 365
)
View Source
const (
	// CertTeleportUser specifies teleport user
	CertTeleportUser = "x-teleport-user"
	// CertTeleportUserCA specifies teleport certificate authority
	CertTeleportUserCA = "x-teleport-user-ca"
	// CertExtensionRole specifies teleport role
	CertExtensionRole = "x-teleport-role"
	// CertExtensionAuthority specifies teleport authority's name
	// that signed this domain
	CertExtensionAuthority = "x-teleport-authority"
	// HostUUIDFile is the file name where the host UUID file is stored
	HostUUIDFile = "host_uuid"
	// CertTeleportClusterName is a name of the teleport cluster
	CertTeleportClusterName = "x-teleport-cluster-name"
	// CertTeleportUserCertificate is the certificate of the authenticated in user.
	CertTeleportUserCertificate = "x-teleport-certificate"
	// ExtIntCertType is an internal extension used to propagate cert type.
	ExtIntCertType = "certtype@teleport"
	// ExtIntCertTypeHost indicates a host-type certificate.
	ExtIntCertTypeHost = "host"
	// ExtIntCertTypeUser indicates a user-type certificate.
	ExtIntCertTypeUser = "user"
)
View Source
const PortStartingNumber = 20000

PortStartingNumber is a starting port number for tests

View Source
const (
	// SelfSignedCertsMsg is a helper message to point users towards helpful documentation.
	SelfSignedCertsMsg = "Your proxy certificate is not trusted or expired. " +
		"Please update the certificate or follow this guide for self-signed certs: https://goteleport.com/docs/setup/admin/self-signed-certs/"
)

Variables

View Source
var (
	// ErrFnCacheClosed is returned from Get when the FnCache context is closed
	ErrFnCacheClosed = errors.New("fncache permanently closed")
)
View Source
var ErrLimitReached = &trace.LimitExceededError{Message: "the read limit is reached"}

ErrLimitReached means that the read limit is reached.

View Source
var ErrUnsuccessfulLockTry = errors.New("could not acquire lock on the file at this time")

ErrUnsuccessfulLockTry designates an error when we temporarily couldn't acquire lock (most probably it was already locked by someone else), another try might succeed.

View Source
var FullJitter = retryutils.NewFullJitter()

FullJitter is a global jitter instance used for one-off jitters. Prefer instantiating a new jitter instance for operations that require repeated calls

View Source
var HalfJitter = retryutils.NewHalfJitter()

HalfJitter is a global jitter instance used for one-off jitters. Prefer instantiating a new jitter instance for operations that require repeated calls.

View Source
var KnownFormatFields = knownFormatFieldsMap{
	// contains filtered or unexported fields
}

KnownFormatFields are the known fields for log entries

View Source
var SafeConfig = jsoniter.Config{
	EscapeHTML:                    false,
	MarshalFloatWith6Digits:       true,
	ObjectFieldMustBeSimpleString: true,
	SortMapKeys:                   true,
}.Froze()

SafeConfig uses jsoniter's ConfigFastest settings but enables map key sorting to ensure CompareAndSwap checks consistently succeed.

View Source
var SeventhJitter = retryutils.NewSeventhJitter()

SeventhJitter is a global jitter instance used for one-off jitters. Prefer instantiating a new jitter instance for operations that require repeated calls.

Functions

func AllowNewlines

func AllowNewlines(s string) string

AllowNewlines escapes all ANSI escape sequences except newlines from string and returns a string that is safe to print on the CLI. This is to ensure that malicious servers can not hide output. For more details, see:

func AsBool

func AsBool(v string) bool

AsBool converts string to bool, in case of the value is empty or unknown, defaults to false

func CalculateSPKI

func CalculateSPKI(cert *x509.Certificate) string

CalculateSPKI the hash value of the SPKI header in a certificate.

func CanUserWriteTo

func CanUserWriteTo(path string) (bool, error)

CanUserWriteTo attempts to check if a user has write access to certain path. It also works around the program being run as root and tries to check the permissions of the user who executed the program as root. This should only be used for string formatting or inconsequential use cases as it's not bullet proof and can report wrong results.

func ChainStreamServerInterceptors

func ChainStreamServerInterceptors(first grpc.StreamServerInterceptor, rest ...grpc.StreamServerInterceptor) grpc.StreamServerInterceptor

ChainStreamServerInterceptors takes 1 or more grpc.StreamServerInterceptors and chains them into a single grpc.StreamServerInterceptor. The first interceptor will be the outer most, while the last interceptor will be the inner most wrapper around the real call.

func ChainUnaryServerInterceptors

func ChainUnaryServerInterceptors(first grpc.UnaryServerInterceptor, rest ...grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor

ChainUnaryServerInterceptors takes 1 or more grpc.UnaryServerInterceptors and chains them into a single grpc.UnaryServerInterceptor. The first interceptor will be the outer most, while the last interceptor will be the inner most wrapper around the real call.

func CheckCertificateFormatFlag

func CheckCertificateFormatFlag(s string) (string, error)

CheckCertificateFormatFlag checks if the certificate format is valid.

func CheckSPKI

func CheckSPKI(pins []string, certs []*x509.Certificate) error

CheckSPKI the passed in pin against the calculated value from a certificate.

func CheckVersion

func CheckVersion(currentVersion, minVersion string) error

CheckVersion compares a version with a minimum version supported.

func ChooseRandomString

func ChooseRandomString(slice []string) string

ChooseRandomString returns a random string from the given slice.

func CipherSuiteMapping

func CipherSuiteMapping(cipherSuites []string) ([]uint16, error)

CipherSuiteMapping transforms Teleport formatted cipher suites strings into uint16 IDs.

func ClickableURL

func ClickableURL(in string) string

ClickableURL fixes address in url to make sure it's clickable, e.g. it replaces "undefined" address like 0.0.0.0 used in network listeners format with loopback 127.0.0.1

func ClientIPFromConn

func ClientIPFromConn(conn net.Conn) (string, error)

ClientIPFromConn extracts host from provided remote address.

func Color

func Color(color int, v interface{}) string

Color formats the string in a terminal escape color

func CompressTarGzArchive

func CompressTarGzArchive(files []string, fileReader ReadStatFS) (*bytes.Buffer, error)

CompressTarGzArchive creates a Tar Gzip archive in memory, reading the files using the provided file reader

func Consolef added in v1.0.0

func Consolef(w io.Writer, log logrus.FieldLogger, component, msg string, params ...interface{})

Consolef prints the same message to a 'ui console' (if defined) and also to the logger with INFO priority

func ContainsExpansion

func ContainsExpansion(val string) bool

ContainsExpansion returns true if value contains expansion syntax, e.g. $1 or ${10}

func CopyStringsMap

func CopyStringsMap(in map[string]string) map[string]string

CopyStringsMap returns a copy of the strings map

func CreateCertificate

func CreateCertificate(principal string, certType uint32) (*ssh.Certificate, ssh.Signer, error)

CreateCertificate creates a valid 2048-bit RSA certificate.

func CreateEllipticCertificate

func CreateEllipticCertificate(principal string, certType uint32) (*ssh.Certificate, ssh.Signer, error)

CreateEllipticCertificate creates a valid, but not supported, ECDSA SSH certificate. This certificate is used to make sure Teleport rejects such certificates.

func CreateTLSConfiguration

func CreateTLSConfiguration(certFile, keyFile string, cipherSuites []uint16) (*tls.Config, error)

CreateTLSConfiguration sets up default TLS configuration

func CryptoRandomHex added in v1.0.0

func CryptoRandomHex(length int) (string, error)

CryptoRandomHex returns a hex-encoded random string generated with a crypto-strong pseudo-random generator. The length parameter controls how many random bytes are generated, and the returned hex string will be twice the length. An error is returned when fewer bytes were generated than length.

func DNSName

func DNSName(hostport string) (string, error)

DNSName extracts DNS name from host:port string.

func DefaultCipherSuites

func DefaultCipherSuites() []uint16

DefaultCipherSuites returns the default list of cipher suites that Teleport supports. By default Teleport only support modern ciphers (Chacha20 and AES GCM) and key exchanges which support perfect forward secrecy (ECDHE).

Note that TLS_RSA_WITH_AES_128_GCM_SHA{256,384} have been dropped due to being banned by HTTP2 which breaks GRPC clients. For more information see: https://tools.ietf.org/html/rfc7540#appendix-A. These two can still be manually added if needed.

func DualPipeNetConn

func DualPipeNetConn(srcAddr net.Addr, dstAddr net.Addr) (*PipeNetConn, *PipeNetConn)

DualPipeAddrConn creates a net.Pipe to connect a client and a server. The two net.Conn instances are wrapped in an addrConn which holds the source and destination addresses.

func EnsureLocalPath

func EnsureLocalPath(customPath string, defaultLocalDir, defaultLocalPath string) (string, error)

EnsureLocalPath makes sure the path exists, or, if omitted results in the subpath in default gravity config directory, e.g.

EnsureLocalPath("/custom/myconfig", ".gravity", "config") -> /custom/myconfig EnsureLocalPath("", ".gravity", "config") -> ${HOME}/.gravity/config

It also makes sure that base dir exists

func EscapeControl

func EscapeControl(s string) string

EscapeControl escapes all ANSI escape sequences from string and returns a string that is safe to print on the CLI. This is to ensure that malicious servers can not hide output. For more details, see:

func Extract

func Extract(r io.Reader, dir string) error

Extract extracts the contents of the specified tarball under dir. The resulting files and directories are created using the current user context. Extract will only unarchive files into dir, and will fail if the tarball tries to write files outside of dir.

func FSTryReadLock

func FSTryReadLock(filePath string) (unlock func() error, err error)

FSTryReadLock tries to grab write lock, returns ErrUnsuccessfulLockTry if lock is already acquired by someone else

func FSTryReadLockTimeout

func FSTryReadLockTimeout(ctx context.Context, filePath string, timeout time.Duration) (unlock func() error, err error)

FSTryReadLockTimeout tries to grab read lock, it's doing it until locks is acquired, or timeout is expired, or context is expired.

func FSTryWriteLock

func FSTryWriteLock(filePath string) (unlock func() error, err error)

FSTryWriteLock tries to grab write lock, returns ErrUnsuccessfulLockTry if lock is already acquired by someone else

func FSTryWriteLockTimeout

func FSTryWriteLockTimeout(ctx context.Context, filePath string, timeout time.Duration) (unlock func() error, err error)

FSTryWriteLockTimeout tries to grab write lock, it's doing it until locks is acquired, or timeout is expired, or context is expired.

func FastMarshal

func FastMarshal(v interface{}) ([]byte, error)

FastMarshal uses the json-iterator library for fast JSON marshaling. Note, this function unmarshals floats with 6 digits precision.

func FastMarshalIndent

func FastMarshalIndent(v interface{}, prefix, indent string) ([]byte, error)

FastMarshal uses the json-iterator library for fast JSON marshaling with indentation. Note, this function unmarshals floats with 6 digits precision.

func FastUnmarshal

func FastUnmarshal(data []byte, v interface{}) error

FastUnmarshal uses the json-iterator library for fast JSON unmarshalling. Note, this function marshals floats with 6 digits precision.

func FatalError added in v1.0.0

func FatalError(err error)

FatalError is for CLI front-ends: it detects gravitational/trace debugging information, sends it to the logger, strips it off and prints a clean message to stderr

func FileExists

func FileExists(fp string) bool

FileExists checks whether a file exists at a given path

func FnCacheGet

func FnCacheGet[T any](ctx context.Context, cache *FnCache, key any, loadfn func(ctx context.Context) (T, error)) (T, error)

FnCacheGet loads the result associated with the supplied key. If no result is currently stored, or the stored result was acquired >ttl ago, then loadfn is used to reload it. Subsequent calls while the value is being loaded/reloaded block until the first call updates the entry. Note that the supplied context can cancel the call to Get, but will not cancel loading. The supplied loadfn should not be canceled just because the specific request happens to have been canceled.

func FormatAlert

func FormatAlert(alert types.ClusterAlert) string

FormatAlert formats and colors the alert message if possible.

func FormatErrorWithNewline

func FormatErrorWithNewline(err error) string

FormatErrorWithNewline returns user friendly error message from error. The error message is escaped if necessary. A newline is added if the error text does not end with a newline.

func GRPCClientStreamErrorInterceptor

func GRPCClientStreamErrorInterceptor(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error)

GRPCClientStreamErrorInterceptor is GPRC client stream interceptor that handles converting errors to the appropriate grpc status error.

func GRPCClientUnaryErrorInterceptor

func GRPCClientUnaryErrorInterceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error

GRPCClientUnaryErrorInterceptor is a GPRC unary client interceptor that handles converting errors to the appropriate grpc status error.

func GRPCServerStreamErrorInterceptor

func GRPCServerStreamErrorInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error

GRPCServerStreamErrorInterceptor is a GPRC server stream interceptor that handles converting errors to the appropriate grpc status error.

func GRPCServerUnaryErrorInterceptor

func GRPCServerUnaryErrorInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error)

GRPCServerUnaryErrorInterceptor is a GPRC unary server interceptor that handles converting errors to the appropriate grpc status error.

func GenerateOTPURL

func GenerateOTPURL(typ string, label string, parameters map[string][]byte) string

GenerateOTPURL returns a OTP Key URL that can be used to construct a HOTP or TOTP key. For more details see: https://github.com/google/google-authenticator/wiki/Key-Uri-Format Example: otpauth://totp/foo:bar@baz.com?secret=qux

func GenerateQRCode

func GenerateQRCode(u string) ([]byte, error)

GenerateQRCode takes in a OTP Key URL and returns a PNG-encoded QR code.

func GenerateSelfSignedSigningCert

func GenerateSelfSignedSigningCert(entity pkix.Name, dnsNames []string, ttl time.Duration) ([]byte, []byte, error)

GenerateSelfSignedSigningCert generates self-signed certificate used for digital signatures

func GetEC2IdentityDocument

func GetEC2IdentityDocument() ([]byte, error)

GetEC2IdentityDocument fetches the PKCS7 RSA2048 InstanceIdentityDocument from the IMDS for this EC2 instance.

func GetEC2NodeID

func GetEC2NodeID() (string, error)

GetEC2NodeID returns the node ID to use for this EC2 instance when using Simplified Node Joining.

func GetIterations

func GetIterations() int

GetIterations provides a simple way to add iterations to the test by setting environment variable "ITERATIONS", by default it returns 1

func GetListenerFile

func GetListenerFile(listener net.Listener) (*os.File, error)

GetListenerFile returns file associated with listener

func GlobToRegexp

func GlobToRegexp(in string) string

GlobToRegexp replaces glob-style standalone wildcard values with real .* regexp-friendly values, does not modify regexp-compatible values, quotes non-wildcard values

func GuessHostIP added in v1.0.0

func GuessHostIP() (ip net.IP, err error)

GuessIP tries to guess an IP address this machine is reachable at on the internal network, always picking IPv4 from the internal address space

If no internal IPs are found, it returns 127.0.0.1 but it never returns an address from the public IP space

func HasBTF

func HasBTF() error

HasBTF checks that the kernel has been compiled with BTF support and that the type information can be opened. Returns nil if BTF is there and accessible, otherwise an error describing the problem.

func HasPrefixAny

func HasPrefixAny(prefix string, values []string) bool

HasPrefixAny determines if any of the string values have the given prefix.

func Host

func Host(hostname string) (string, error)

Host extracts host from host:port string

func InitCLIParser added in v1.0.0

func InitCLIParser(appName, appHelp string) (app *kingpin.Application)

InitCLIParser configures kingpin command line args parser with some defaults common for all Teleport CLI tools

func InitLogger

func InitLogger(purpose LoggingPurpose, level logrus.Level, verbose ...bool)

InitLogger configures the global logger for a given purpose / verbosity level

func InitLoggerForTests added in v1.0.0

func InitLoggerForTests()

InitLoggerForTests initializes the standard logger for tests.

func IsCertExpiredError

func IsCertExpiredError(err error) bool

IsCertExpiredError specifies whether this error indicates expired SSH certificate

func IsConnectionRefused

func IsConnectionRefused(err error) bool

IsConnectionRefused returns true if the given err is "connection refused" error.

func IsDir added in v1.0.0

func IsDir(path string) bool

IsDir is a helper function to quickly check if a given path is a valid directory

func IsEC2NodeID

func IsEC2NodeID(id string) bool

IsEC2NodeID returns true if the given ID looks like an EC2 node ID. Uses a simple regex to check. Node IDs are almost always UUIDs when set automatically, but can be manually overridden by admins. If someone manually sets a host ID that looks like one of our generated EC2 node IDs, they may be able to trick this function, so don't use it for any critical purpose.

func IsExpiredCredentialError

func IsExpiredCredentialError(err error) bool

IsExpiredCredentialError checks if an error corresponds to expired credentials.

func IsFailedToSendCloseNotifyError

func IsFailedToSendCloseNotifyError(err error) bool

IsFailedToSendCloseNotifyError returns true if the provided error is the "tls: failed to send closeNotify".

func IsFile added in v1.0.0

func IsFile(path string) bool

IsFile is a convenience helper to check if the given path is a regular file

func IsGroupMember

func IsGroupMember(gid int) (bool, error)

IsGroupMember returns whether currently logged user is a member of a group

func IsHandshakeFailedError added in v1.0.0

func IsHandshakeFailedError(err error) bool

IsHandshakeFailedError specifies whether this error indicates failed handshake

func IsLocalhost added in v1.0.0

func IsLocalhost(host string) bool

IsLocalhost returns true if this is a local hostname or ip

func IsOKNetworkError

func IsOKNetworkError(err error) bool

IsOKNetworkError returns true if the provided error received from a network operation is one of those that usually indicate normal connection close. If the error is a trace.Aggregate, all the errors must be OK network errors.

func IsPredicateError

func IsPredicateError(err error) bool

IsPredicateError determines if the error is from failing to parse predicate expression by checking if the error as a string contains predicate keywords.

func IsSelfSigned

func IsSelfSigned(certificateChain []*x509.Certificate) bool

IsSelfSigned checks if the certificate is a self-signed certificate. To check if a certificate is self-signed, we make sure that only one certificate is in the chain and that the SubjectKeyId and AuthorityKeyId match.

From RFC5280: https://tools.ietf.org/html/rfc5280#section-4.2.1.1

The signature on a self-signed certificate is generated with the private
key associated with the certificate's subject public key. (This
proves that the issuer possesses both the public and private keys.)
In this case, the subject and authority key identifiers would be
identical, but only the subject key identifier is needed for
certification path building.

func IsUntrustedCertErr

func IsUntrustedCertErr(err error) bool

IsUntrustedCertErr checks if an error is an untrusted cert error.

func IsUseOfClosedNetworkError

func IsUseOfClosedNetworkError(err error) bool

IsUseOfClosedNetworkError returns true if the specified error indicates the use of a closed network connection.

func IsValidHostname

func IsValidHostname(hostname string) bool

IsValidHostname checks if a string represents a valid hostname.

func KernelVersion

func KernelVersion() (*semver.Version, error)

KernelVersion parses /proc/sys/kernel/osrelease and returns the kernel version of the host. This only returns something meaningful on Linux.

func MarshalPrivateKey

func MarshalPrivateKey(key crypto.Signer) ([]byte, []byte, error)

MarshalPrivateKey will return a PEM encoded crypto.Signer. Only supports RSA private keys.

func MarshalPublicKey

func MarshalPublicKey(signer crypto.Signer) ([]byte, error)

MarshalPublicKey returns a PEM encoded public key for a given crypto.Signer

func MaxInt64

func MaxInt64(x, y int64) int64

MaxInt64 returns the numerically greater of two signed 64-bit integers.

func MinInt64

func MinInt64(x, y int64) int64

MinInt64 returns the numerically lesser of two signed 64-bit integers.

func MinTTL

func MinTTL(a, b time.Duration) time.Duration

MinTTL finds min non 0 TTL duration, if both durations are 0, fails

func MinVerWithoutPreRelease

func MinVerWithoutPreRelease(currentVersion, minVersion string) (bool, error)

MinVerWithoutPreRelease compares semver strings, but skips prerelease. This allows to compare two versions and ignore dev,alpha,beta, etc. strings.

func MkdirAll

func MkdirAll(targetDirectory string, mode os.FileMode) error

MkdirAll creates directory and subdirectories

func MultiCloser

func MultiCloser(closers ...io.Closer) io.Closer

MultiCloser implements io.Close, it sequentially calls Close() on each object

func NetAddrsToStrings

func NetAddrsToStrings(netAddrs []NetAddr) []string

NetAddrsToStrings takes a list of netAddrs and returns a list of address strings.

func NewCertPoolFromPath

func NewCertPoolFromPath(path string) (*x509.CertPool, error)

NewCertPoolFromPath creates a new x509.CertPool from provided path.

func NewDefaultLinear

func NewDefaultLinear() *retryutils.Linear

NewDefaultLinear creates a linear retry using a half jitter, 10s step, and maxing out at 1 minute. These values were selected by reviewing commonly used parameters elsewhere in the code base, which (at the time of writing) seem to converge on approximately this configuration for "critical but potentially load-inducing" operations like cache watcher registration and auth connector setup. It also includes an auto-reset value of 5m. Auto-reset is less commonly used, and if used should probably be shorter, but 5m is a reasonable safety net to reduce the impact of accidental misuse.

func NewLogger

func NewLogger() *logrus.Logger

NewLogger creates a new empty logger

func NewLoggerForTests

func NewLoggerForTests() *logrus.Logger

NewLoggerForTests creates a new logger for test environment

func NewStdlogger

func NewStdlogger(logger LeveledOutputFunc, component string) *stdlog.Logger

NewStdlogger creates a new stdlib logger that uses the specified leveled logger for output and the given component as a logging prefix.

func NilCloser

func NilCloser(r io.Closer) io.Closer

NilCloser returns closer if it's not nil otherwise returns a nop closer

func NodeIDFromIID

func NodeIDFromIID(iid *imds.InstanceIdentityDocument) string

NodeIDFromIID returns the node ID that must be used for nodes joining with the given Instance Identity Document.

func NopWriteCloser

func NopWriteCloser(r io.Writer) io.WriteCloser

NopWriteCloser returns a WriteCloser with a no-op Close method wrapping the provided Writer w

func NormalizePath

func NormalizePath(path string) (string, error)

NormalizePath normalises path, evaluating symlinks and converting local paths to absolute

func OSRelease

func OSRelease(rel io.Reader) (map[string]string, error)

func ObeyIdleTimeout

func ObeyIdleTimeout(conn net.Conn, timeout time.Duration, ownerName string) net.Conn

ObeyIdleTimeout wraps an existing network connection with timeout-obeying Write() and Read() - it will drop the connection after 'timeout' on idle

Example: ObeyIdletimeout(conn, time.Second * 60, "api server").

func OpaqueAccessDenied

func OpaqueAccessDenied(err error) error

OpaqueAccessDenied returns a generic NotFound instead of AccessDenied so as to avoid leaking the existence of secret resources.

func OpenFile

func OpenFile(path string) (*os.File, error)

OpenFile opens file and returns file handle

func ParseAdvertiseAddr

func ParseAdvertiseAddr(advertiseIP string) (string, string, error)

ParseAdvertiseAddr validates advertise address, makes sure it's not an unreachable or multicast address returns address split into host and port, port could be empty if not specified

func ParseOnOff

func ParseOnOff(parameterName, val string, defaultValue bool) (bool, error)

ParseOnOff parses whether value is "on" or "off", parameterName is passed for error reporting purposes, defaultValue is returned when no value is set

func ParsePrivateKey

func ParsePrivateKey(bytes []byte) (crypto.Signer, error)

ParsePrivateKey parses a PEM encoded private key and returns a crypto.Signer. Only supports RSA private keys.

func ParsePrivateKeyDER

func ParsePrivateKeyDER(der []byte) (crypto.Signer, error)

ParsePrivateKeyDER parses unencrypted DER-encoded private key

func ParsePrivateKeyPEM

func ParsePrivateKeyPEM(bytes []byte) (crypto.Signer, error)

ParsePrivateKeyPEM parses PEM-encoded private key

func ParsePublicKey

func ParsePublicKey(bytes []byte) (crypto.PublicKey, error)

ParsePublicKey parses a PEM encoded public key and returns a crypto.PublicKey. Only support RSA public keys.

func PercentUsed

func PercentUsed(path string) (float64, error)

PercentUsed returns percentage of disk space used. The percentage of disk space used is calculated from (total blocks - free blocks)/total blocks. The value is rounded to the nearest whole integer.

func PrintVersion added in v1.0.0

func PrintVersion()

PrintVersion prints human readable version

func ProxyConn

func ProxyConn(ctx context.Context, client, server io.ReadWriteCloser) error

ProxyConn launches a double-copy loop that proxies traffic between the provided client and server connections.

Exits when one or both copies stop, or when the context is canceled, and closes both connections.

func RandomDuration added in v1.0.0

func RandomDuration(max time.Duration) time.Duration

RandomDuration returns a duration in a range [0, max)

func ReadAtMost

func ReadAtMost(r io.Reader, limit int64) ([]byte, error)

ReadAtMost reads up to limit bytes from r, and reports an error when limit bytes are read.

func ReadCertificates

func ReadCertificates(certificateChainBytes []byte) ([]*x509.Certificate, error)

ReadCertificates parses PEM encoded bytes that can contain one or multiple certificates and returns a slice of x509.Certificate.

func ReadCertificatesFromPath

func ReadCertificatesFromPath(path string) ([]*x509.Certificate, error)

ReadCertificatesFromPath parses PEM encoded certificates from provided path.

func ReadEnvironmentFile

func ReadEnvironmentFile(filename string) ([]string, error)

ReadEnvironmentFile will read environment variables from a passed in location. Lines that start with "#" or empty lines are ignored. Assignments are in the form name=value and no variable expansion occurs.

func ReadHostUUID added in v1.0.0

func ReadHostUUID(dataDir string) (string, error)

ReadHostUUID reads host UUID from the file in the data dir

func ReadOrMakeHostUUID added in v1.0.0

func ReadOrMakeHostUUID(dataDir string) (string, error)

ReadOrMakeHostUUID looks for a hostid file in the data dir. If present, returns the UUID from it, otherwise generates one

func ReadPath

func ReadPath(path string) ([]byte, error)

ReadPath reads file contents

func ReadYAML

func ReadYAML(reader io.Reader) (interface{}, error)

ReadYAML can unmarshal a stream of documents, used in tests.

func RemoveFromSlice

func RemoveFromSlice(slice []string, values ...string) []string

RemoveFromSlice makes a copy of the slice and removes the passed in values from the copy.

func ReplaceInSlice

func ReplaceInSlice(s []string, old string, new string) []string

ReplaceInSlice replaces element old with new and returns a new slice.

func ReplaceLocalhost added in v1.0.0

func ReplaceLocalhost(addr, replaceWith string) string

ReplaceLocalhost checks if a given address is link-local (like 0.0.0.0 or 127.0.0.1) and replaces it with the IP taken from replaceWith, preserving the original port

Both addresses are in "host:port" format The function returns the original value if it encounters any problems with parsing

func ReplaceRegexp

func ReplaceRegexp(expression string, replaceWith string, input string) (string, error)

ReplaceRegexp replaces value in string, accepts regular expression and simplified wildcard syntax, it has several important differeneces with standard lib regexp replacer: * Wildcard globs '*' are treated as regular expression .* expression * Expression is treated as regular expression if it starts with ^ and ends with $ * Full match is expected, partial replacements ignored * If there is no match, returns a NotFound error

func ReplaceRegexpWithConfig

func ReplaceRegexpWithConfig(expression string, replaceWith string, input string, config RegexpConfig) (string, error)

ReplaceRegexpWithConfig behaves exactly like ReplaceRegexp but its behavior can be customized

func ReplaceUnspecifiedHost

func ReplaceUnspecifiedHost(addr *NetAddr, defaultPort int) string

ReplaceUnspecifiedHost replaces unspecified "0.0.0.0" with localhost since "0.0.0.0" is never a valid principal (auth server explicitly removes it when issuing host certs) and when a reverse tunnel client used establishes SSH reverse tunnel connection the host is validated against the valid principal list.

func Round

func Round(x float64) float64

Round returns the nearest integer, rounding half away from zero.

Special cases are:

Round(±0) = ±0
Round(±Inf) = ±Inf
Round(NaN) = NaN

Note: Copied from Go standard library to support Go 1.9.7 releases. This function was added in the standard library in Go 1.10.

func Roundtrip

func Roundtrip(addr string) (string, error)

Roundtrip is a single connection simplistic HTTP client that allows us to bypass a connection pool to test load balancing used in tests, as it only supports GET request on /

func RoundtripWithConn

func RoundtripWithConn(conn net.Conn) (string, error)

RoundtripWithConn uses HTTP GET on the existing connection, used in tests as it only performs GET request on /

func SetupTLSConfig

func SetupTLSConfig(config *tls.Config, cipherSuites []uint16)

SetupTLSConfig sets up cipher suites in existing TLS config

func SliceMatchesRegex

func SliceMatchesRegex(input string, expressions []string) (bool, error)

SliceMatchesRegex checks if input matches any of the expressions. The match is always evaluated as a regex either an exact match or regexp.

func SplitHostPort

func SplitHostPort(hostname string) (string, string, error)

SplitHostPort splits host and port and checks that host is not empty

func SplitIdentifiers

func SplitIdentifiers(s string) []string

SplitIdentifiers splits list of identifiers by commas/spaces/newlines. Helpful when accepting lists of identifiers in CLI (role names, request IDs, etc).

func StatDir

func StatDir(path string) (os.FileInfo, error)

StatDir stats directory, returns error if file exists, but not a directory

func StatFile

func StatFile(path string) (os.FileInfo, error)

StatFile stats path, returns error if it exists but a directory.

func StoreErrorOf

func StoreErrorOf(f func() error, err *error)

StoreErrorOf stores the error returned by f within *err.

func StringMapsEqual

func StringMapsEqual(a, b map[string]string) bool

StringMapsEqual returns true if two strings maps are equal

func StringSliceSubset

func StringSliceSubset(a []string, b []string) error

StringSliceSubset returns true if b is a subset of a.

func StringsSet

func StringsSet(in []string) map[string]struct{}

StringsSet creates set of string (map[string]struct{}) from a list of strings

func StringsSliceFromSet

func StringsSliceFromSet(in map[string]struct{}) []string

StringsSliceFromSet returns a sorted strings slice from set

func SwitchLoggerToSyslog

func SwitchLoggerToSyslog(logger *log.Logger) error

SwitchLoggerToSyslog tells the logger to send the output to syslog.

func SwitchLoggingtoSyslog

func SwitchLoggingtoSyslog() error

SwitchLoggingtoSyslog tells the default logger to send the output to syslog. This code is behind a build flag because Windows does not support syslog.

func TLSCertToX509

func TLSCertToX509(cert tls.Certificate) (*x509.Certificate, error)

TLSCertToX509 is a helper function that converts a tls.Certificate into an *x509.Certificate

func TLSConfig

func TLSConfig(cipherSuites []uint16) *tls.Config

TLSConfig returns default TLS configuration strong defaults.

func TLSDial

func TLSDial(ctx context.Context, dial DialWithContextFunc, network, addr string, tlsConfig *tls.Config) (*tls.Conn, error)

TLSDial dials and establishes TLS connection using custom dialer is similar to tls.DialWithDialer

func ThisFunction

func ThisFunction() string

ThisFunction returns calling function name

func ToJSON

func ToJSON(data []byte) ([]byte, error)

ToJSON converts a single YAML document into a JSON document or returns an error. If the document appears to be JSON the YAML decoding path is not used (so that error messages are JSON specific). Creds to: k8s.io for the code

func ToTTL

func ToTTL(c clockwork.Clock, tm time.Time) time.Duration

ToTTL converts expiration time to TTL duration relative to current time as provided by clock

func TryReadValueAsFile

func TryReadValueAsFile(value string) (string, error)

TryReadValueAsFile is a utility function to read a value from the disk if it looks like an absolute path, otherwise, treat it as a value. It only support absolute paths to avoid ambiguity in interpretation of the value

func UintSliceSubset

func UintSliceSubset(a []uint16, b []uint16) error

UintSliceSubset returns true if b is a subset of a.

func UpdateAppUsageTemplate

func UpdateAppUsageTemplate(app *kingpin.Application, args []string)

UpdateAppUsageTemplate updates usage template for kingpin applications by pre-parsing the arguments then applying any changes to the usage template if necessary.

func UserMessageFromError added in v1.0.0

func UserMessageFromError(err error) string

UserMessageFromError returns user-friendly error message from error. The error message will be formatted for output depending on the debug flag

func VerifyCertificateChain

func VerifyCertificateChain(certificateChain []*x509.Certificate) error

VerifyCertificateChain reads in chain of certificates and makes sure the chain from leaf to root is valid. This ensures that clients (web browsers and CLI) won't have problem validating the chain.

func VerifyCertificateExpiry

func VerifyCertificateExpiry(c *x509.Certificate, clock clockwork.Clock) error

VerifyCertificateExpiry checks the certificate's expiration status.

func VersionBeforeAlpha

func VersionBeforeAlpha(version string) string

VersionBeforeAlpha appends "-aa" to the version so that it comes before <version>-alpha. This ban be used to make version checks work during development.

func WriteCloserWithContext

func WriteCloserWithContext(ctx context.Context, closer WriteContextCloser) io.WriteCloser

WriteCloserWithContext converts ContextCloser to io.Closer, whenever new Close method will be called, the ctx will be passed to it

func WriteHostUUID added in v1.0.0

func WriteHostUUID(dataDir string, id string) error

WriteHostUUID writes host UUID into a file

func WriteYAML

func WriteYAML(w io.Writer, values interface{}) error

WriteYAML detects whether value is a list and marshals multiple documents delimited by `---`, otherwise, marshals a single value

Types

type Anonymizer

type Anonymizer interface {
	// Anonymize returns anonymized string from the provided data
	Anonymize(data []byte) string
}

Anonymizer defines an interface for anonymizing data

type BufferSyncPool

type BufferSyncPool struct {
	sync.Pool
	// contains filtered or unexported fields
}

BufferSyncPool is a sync pool of bytes.Buffer

func NewBufferSyncPool

func NewBufferSyncPool(size int64) *BufferSyncPool

NewBufferSyncPool returns a new instance of sync pool of bytes.Buffers that creates new buffers with preallocated underlying buffer of size

func (*BufferSyncPool) Get

func (b *BufferSyncPool) Get() *bytes.Buffer

Get returns a new or already allocated buffer

func (*BufferSyncPool) Put

func (b *BufferSyncPool) Put(buf *bytes.Buffer)

Put resets the buffer (does not free the memory) and returns it back to the pool. Users should be careful not to use the buffer (e.g. via Bytes) after it was returned

func (*BufferSyncPool) Size

func (b *BufferSyncPool) Size() int64

Size returns default allocated buffer size

type CaptureNBytesWriter

type CaptureNBytesWriter struct {
	// contains filtered or unexported fields
}

CaptureNBytesWriter is an io.Writer thats captures up to first n bytes of the incoming data in memory, and then it ignores the rest of the incoming data.

func NewCaptureNBytesWriter

func NewCaptureNBytesWriter(max int) *CaptureNBytesWriter

NewCaptureNBytesWriter creates a new CaptureNBytesWriter.

func (CaptureNBytesWriter) Bytes

func (w CaptureNBytesWriter) Bytes() []byte

Bytes returns all captured bytes.

func (*CaptureNBytesWriter) Write

func (w *CaptureNBytesWriter) Write(p []byte) (int, error)

Write implements io.Writer.

type CircularBuffer

type CircularBuffer struct {
	sync.Mutex
	// contains filtered or unexported fields
}

CircularBuffer implements an in-memory circular buffer of predefined size

func NewCircularBuffer

func NewCircularBuffer(size int) (*CircularBuffer, error)

NewCircularBuffer returns a new instance of a circular buffer that will hold size elements before it rotates

func (*CircularBuffer) Add

func (t *CircularBuffer) Add(d float64)

Add pushes a new item onto the buffer

func (*CircularBuffer) Data

func (t *CircularBuffer) Data(n int) []float64

Data returns the most recent n elements in the correct order

type CloseBroadcaster added in v1.0.0

type CloseBroadcaster struct {
	sync.Once
	C chan struct{}
}

CloseBroadcaster is a helper struct that implements io.Closer and uses channel to broadcast it's closed state once called

func NewCloseBroadcaster added in v1.0.0

func NewCloseBroadcaster() *CloseBroadcaster

NewCloseBroadcaster returns new instance of close broadcaster

func (*CloseBroadcaster) Close added in v1.0.0

func (b *CloseBroadcaster) Close() error

Close closes channel (once) to start broadcasting it's closed state

type CloserConn

type CloserConn struct {
	net.Conn
	// contains filtered or unexported fields
}

CloserConn wraps connection and attaches additional closers to it

func NewCloserConn

func NewCloserConn(conn net.Conn, closers ...io.Closer) *CloserConn

NewCloserConn returns new connection wrapper that when closed will also close passed closers

func (*CloserConn) AddCloser

func (c *CloserConn) AddCloser(closer io.Closer)

AddCloser adds any closer in ctx that will be called whenever server closes session channel

func (*CloserConn) Close

func (c *CloserConn) Close() error

Close connection, all closers, and cancel context.

func (*CloserConn) Context

func (c *CloserConn) Context() context.Context

Context returns a context that is canceled once the connection is closed.

func (*CloserConn) Wait

func (c *CloserConn) Wait()

Wait for connection to close.

type DialWithContextFunc

type DialWithContextFunc func(ctx context.Context, network, addr string) (net.Conn, error)

DialWithContext dials with context

type Fields

type Fields map[string]interface{}

Fields represents a generic string-keyed map.

func (Fields) GetInt

func (f Fields) GetInt(key string) int

GetInt returns an int representation of a field.

func (Fields) GetString

func (f Fields) GetString(key string) string

GetString returns a string representation of a field.

func (Fields) GetStrings

func (f Fields) GetStrings(key string) []string

GetStrings returns a slice-of-strings representation of a field.

func (Fields) GetTime

func (f Fields) GetTime(key string) time.Time

GetTime returns a time.Time representation of a field.

func (Fields) HasField

func (f Fields) HasField(key string) bool

HasField returns true if the field exists.

type FieldsCondition

type FieldsCondition func(Fields) bool

FieldsCondition is a boolean function on Fields.

func ToFieldsCondition

func ToFieldsCondition(expr *types.WhereExpr) (FieldsCondition, error)

ToFieldsCondition converts a WhereExpr into a FieldsCondition.

type FileNode

type FileNode struct {
	Parent string `json:"parent"`
	Name   string `json:"name"`
	Dir    bool   `json:"bool"`
	Size   int64  `json:"size"`
	Mode   int64  `json:"mode"`
}

type FnCache

type FnCache struct {
	// contains filtered or unexported fields
}

FnCache is a helper for temporarily storing the results of regularly called functions. This helper is used to limit the amount of backend reads that occur while the primary cache is unhealthy. Most resources do not require this treatment, but certain resources (cas, nodes, etc) can be loaded on a per-request basis and can cause significant numbers of backend reads if the cache is unhealthy or taking a while to init.

func NewFnCache

func NewFnCache(cfg FnCacheConfig) (*FnCache, error)

type FnCacheConfig

type FnCacheConfig struct {
	// TTL is the time to live for cache entries.
	TTL time.Duration
	// Clock is the clock used to determine the current time.
	Clock clockwork.Clock
	// Context is the context used to cancel the cache. All loadfns
	// will be provided this context.
	Context context.Context
	// ReloadOnErr causes entries to be reloaded immediately if
	// the currently loaded value is an error. Note that all concurrent
	// requests registered before load completes still observe the
	// same error. This option is only really useful for longer TTLs.
	ReloadOnErr bool
	// CleanupInterval is the interval at which cleanups occur (defaults to
	// 16x the supplied TTL). Longer cleanup intervals are appropriate for
	// caches where keys are unlikely to become orphaned. Shorter cleanup
	// intervals should be used when keys regularly become orphaned.
	CleanupInterval time.Duration
}

func (*FnCacheConfig) CheckAndSetDefaults

func (c *FnCacheConfig) CheckAndSetDefaults() error

type HMACAnonymizer

type HMACAnonymizer struct {
	// contains filtered or unexported fields
}

hmacAnonymizer implements anonymization using HMAC

func NewHMACAnonymizer

func NewHMACAnonymizer(key string) (*HMACAnonymizer, error)

NewHMACAnonymizer returns a new HMAC-based anonymizer

func (*HMACAnonymizer) Anonymize

func (a *HMACAnonymizer) Anonymize(data []byte) string

Anonymize anonymizes the provided data using HMAC

type InMemoryFile

type InMemoryFile struct {
	// contains filtered or unexported fields
}

InMemoryFile stores the required properties to emulate a File in memory It contains the File properties like name, size, mode It also contains the File contents It does not support folders

func NewInMemoryFile

func NewInMemoryFile(name string, mode fs.FileMode, modTime time.Time, content []byte) *InMemoryFile

func (*InMemoryFile) Content

func (fi *InMemoryFile) Content() []byte

Content returns the file bytes

func (*InMemoryFile) IsDir

func (fi *InMemoryFile) IsDir() bool

IsDir checks whether the file is a directory

func (*InMemoryFile) ModTime

func (fi *InMemoryFile) ModTime() time.Time

ModTime returns the last modification time

func (*InMemoryFile) Mode

func (fi *InMemoryFile) Mode() fs.FileMode

Mode returns the fs.FileMode

func (*InMemoryFile) Name

func (fi *InMemoryFile) Name() string

Name returns the file's name

func (*InMemoryFile) Size

func (fi *InMemoryFile) Size() int64

Size returns the file size (calculated when writing the file)

func (*InMemoryFile) Sys

func (fi *InMemoryFile) Sys() interface{}

Sys is platform independent InMemoryFile's implementation is no-op

type JSONFormatter

type JSONFormatter struct {
	log.JSONFormatter

	ExtraFields []string
	// contains filtered or unexported fields
}

JSONFormatter implements the logrus.Formatter interface and adds extra fields to log entries

func NewTestJSONFormatter

func NewTestJSONFormatter() *JSONFormatter

func (*JSONFormatter) CheckAndSetDefaults

func (j *JSONFormatter) CheckAndSetDefaults() error

CheckAndSetDefaults checks and sets log format configuration

func (*JSONFormatter) Format

func (j *JSONFormatter) Format(e *log.Entry) ([]byte, error)

Format implements logrus.Formatter interface

type JumpHost

type JumpHost struct {
	// Username to login as
	Username string
	// Addr is a target addr
	Addr NetAddr
}

JumpHost is a target jump host

func ParseProxyJump

func ParseProxyJump(in string) ([]JumpHost, error)

ParseProxyJump parses strings like user@host:port,bob@host:port

type KeyStore

type KeyStore struct {
	// contains filtered or unexported fields
}

KeyStore is used to sign and decrypt data using X509 digital signatures.

func ParseKeyStorePEM

func ParseKeyStorePEM(keyPEM, certPEM string) (*KeyStore, error)

ParseKeyStorePEM parses signing key store from PEM encoded key pair

func (*KeyStore) GetKeyPair

func (ks *KeyStore) GetKeyPair() (*rsa.PrivateKey, []byte, error)

type LeveledOutputFunc

type LeveledOutputFunc func(args ...interface{})

LeveledOutputFunc describes a function that emits given arguments at a specific level to an underlying logger

type LoadBalancer

type LoadBalancer struct {
	sync.RWMutex

	*log.Entry
	// contains filtered or unexported fields
}

LoadBalancer implements naive round robin TCP load balancer used in tests.

func NewLoadBalancer

func NewLoadBalancer(ctx context.Context, frontend NetAddr, backends ...NetAddr) (*LoadBalancer, error)

NewLoadBalancer returns new load balancer listening on frontend and redirecting requests to backends using round robin algo

func NewRandomLoadBalancer

func NewRandomLoadBalancer(ctx context.Context, frontend NetAddr, backends ...NetAddr) (*LoadBalancer, error)

NewRandomLoadBalancer returns new load balancer listening on frontend and redirecting requests to backends randomly.

func (*LoadBalancer) AddBackend

func (l *LoadBalancer) AddBackend(b NetAddr)

AddBackend adds backend

func (*LoadBalancer) Addr

func (l *LoadBalancer) Addr() net.Addr

Addr returns the frontend listener address. Call this after Listen, otherwise Addr returns nil.

func (*LoadBalancer) Close

func (l *LoadBalancer) Close() error

func (*LoadBalancer) Listen

func (l *LoadBalancer) Listen() error

Listen creates a listener on the frontend addr

func (*LoadBalancer) RemoveBackend

func (l *LoadBalancer) RemoveBackend(b NetAddr) error

RemoveBackend removes backend

func (*LoadBalancer) Serve

func (l *LoadBalancer) Serve() error

Serve starts accepting connections

func (*LoadBalancer) Wait

func (l *LoadBalancer) Wait()

Wait is here to workaround issue https://github.com/golang/go/issues/10527 in tests

type Logger

type Logger interface {
	logrus.FieldLogger
	// GetLevel specifies the level at which this logger
	// value is logging
	GetLevel() logrus.Level
	// SetLevel sets the logger's level to the specified value
	SetLevel(level logrus.Level)
}

Logger describes a logger value

func WrapLogger

func WrapLogger(logger *logrus.Entry) Logger

WrapLogger wraps an existing logger entry and returns an value satisfying the Logger interface

type LoggingPurpose

type LoggingPurpose int
const (
	LoggingForDaemon LoggingPurpose = iota
	LoggingForCLI
)

type NetAddr

type NetAddr struct {
	// Addr is the host:port address, like "localhost:22"
	Addr string `json:"addr"`
	// AddrNetwork is the type of a network socket, like "tcp" or "unix"
	AddrNetwork string `json:"network,omitempty"`
	// Path is a socket file path, like '/var/path/to/socket' in "unix:///var/path/to/socket"
	Path string `json:"path,omitempty"`
}

NetAddr is network address that includes network, optional path and host port

func AddrsFromStrings

func AddrsFromStrings(s apiutils.Strings, defaultPort int) ([]NetAddr, error)

AddrsFromStrings returns strings list converted to address list

func DialAddrFromListenAddr

func DialAddrFromListenAddr(listenAddr NetAddr) NetAddr

DialAddrFromListenAddr returns dial address from listen address

func FromAddr

func FromAddr(a net.Addr) NetAddr

FromAddr returns NetAddr from golang standard net.Addr

func JoinAddrSlices

func JoinAddrSlices(a []NetAddr, b []NetAddr) []NetAddr

JoinAddrSlices joins two addr slices and returns a resulting slice

func MustParseAddr added in v1.0.0

func MustParseAddr(a string) *NetAddr

MustParseAddr parses the provided string into NetAddr or panics on an error

func MustParseAddrList

func MustParseAddrList(aList ...string) []NetAddr

MustParseAddrList parses the provided list of strings into a NetAddr list or panics on error

func ParseAddr

func ParseAddr(a string) (*NetAddr, error)

ParseAddr takes strings like "tcp://host:port/path" and returns *NetAddr or an error

func ParseAddrs

func ParseAddrs(addrs []string) (result []NetAddr, err error)

ParseAddrs parses the provided slice of strings as a slice of NetAddr's.

func ParseHostPortAddr added in v1.0.0

func ParseHostPortAddr(hostport string, defaultPort int) (*NetAddr, error)

ParseHostPortAddr takes strings like "host:port" and returns *NetAddr or an error

If defaultPort == -1 it expects 'hostport' string to have it

func (*NetAddr) FullAddress

func (a *NetAddr) FullAddress() string

FullAddress returns full address including network and address (tcp://0.0.0.0:1243)

func (*NetAddr) Host

func (a *NetAddr) Host() string

Host returns host part of address without port

func (*NetAddr) IsEmpty

func (a *NetAddr) IsEmpty() bool

IsEmpty returns true if address is empty

func (*NetAddr) IsHostUnspecified

func (a *NetAddr) IsHostUnspecified() bool

IsHostUnspecified returns true if this address' host is unspecified.

func (*NetAddr) IsLocal added in v1.0.0

func (a *NetAddr) IsLocal() bool

IsLocal returns true if this is a local address

func (*NetAddr) IsLoopback added in v1.0.0

func (a *NetAddr) IsLoopback() bool

IsLoopback returns true if this is a loopback address

func (*NetAddr) MarshalYAML added in v1.0.0

func (a *NetAddr) MarshalYAML() (interface{}, error)

MarshalYAML defines how a network address should be marshaled to a string

func (*NetAddr) Network

func (a *NetAddr) Network() string

Network returns the scheme for this network address (tcp or unix)

func (*NetAddr) Port

func (a *NetAddr) Port(defaultPort int) int

Port returns defaultPort if no port is set or is invalid, the real port otherwise

func (*NetAddr) Set

func (a *NetAddr) Set(s string) error

func (*NetAddr) String

func (a *NetAddr) String() string

String returns address without network (0.0.0.0:1234)

func (*NetAddr) UnmarshalYAML

func (a *NetAddr) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML defines how a string can be unmarshalled into a network address

type OpenFileWithFlagsFunc

type OpenFileWithFlagsFunc func(name string, flag int, perm os.FileMode) (*os.File, error)

OpenFileWithFlagsFunc defines a function used to open files providing options.

type PipeNetConn

type PipeNetConn struct {
	// contains filtered or unexported fields
}

PipeNetConn implements net.Conn from a provided io.Reader,io.Writer and io.Closer

func NewPipeNetConn

func NewPipeNetConn(reader io.Reader,
	writer io.Writer,
	closer io.Closer,
	fakelocalAddr net.Addr,
	fakeRemoteAddr net.Addr) *PipeNetConn

NewPipeNetConn constructs a new PipeNetConn, providing a net.Conn implementation synthesized from the supplied io.Reader, io.Writer & io.Closer.

func (*PipeNetConn) Close

func (nc *PipeNetConn) Close() error

func (*PipeNetConn) LocalAddr

func (nc *PipeNetConn) LocalAddr() net.Addr

func (*PipeNetConn) Read

func (nc *PipeNetConn) Read(buf []byte) (n int, e error)

func (*PipeNetConn) RemoteAddr

func (nc *PipeNetConn) RemoteAddr() net.Addr

func (*PipeNetConn) SetDeadline

func (nc *PipeNetConn) SetDeadline(t time.Time) error

func (*PipeNetConn) SetReadDeadline

func (nc *PipeNetConn) SetReadDeadline(t time.Time) error

func (*PipeNetConn) SetWriteDeadline

func (nc *PipeNetConn) SetWriteDeadline(t time.Time) error

func (*PipeNetConn) Write

func (nc *PipeNetConn) Write(buf []byte) (n int, e error)

type PortList added in v1.0.0

type PortList struct {
	sync.Mutex
	// contains filtered or unexported fields
}

PortList is a list of TCP ports.

func GetFreeTCPPorts added in v1.0.0

func GetFreeTCPPorts(n int, offset ...int) (PortList, error)

GetFreeTCPPorts returns n ports starting from port 20000.

func (*PortList) Pop added in v1.0.0

func (p *PortList) Pop() string

Pop returns a value from the list, it panics if the value is not there

func (*PortList) PopInt

func (p *PortList) PopInt() int

PopInt returns a value from the list, it panics if not enough values were allocated

func (*PortList) PopIntSlice

func (p *PortList) PopIntSlice(num int) []int

PopIntSlice returns a slice of values from the list, it panics if not enough ports were allocated

type PredicateError

type PredicateError struct {
	Err error
}

func (PredicateError) Error

func (p PredicateError) Error() string

type ReadStatFS

type ReadStatFS interface {
	fs.ReadFileFS
	fs.StatFS
}

ReadStatFS combines two interfaces: fs.ReadFileFS and fs.StatFS We need both when creating the archive to be able to: - read file contents - `ReadFile` provided by fs.ReadFileFS - set the correct file permissions - `Stat() ... Mode()` provided by fs.StatFS

type RegexpConfig

type RegexpConfig struct {
	// IgnoreCase specifies whether matching is case-insensitive
	IgnoreCase bool
}

RegexpConfig defines the configuration of the regular expression matcher

type RepeatReader

type RepeatReader struct {
	// contains filtered or unexported fields
}

RepeatReader repeats the same byte count times without allocating any data, the single instance of the repeat reader is not goroutine safe

func NewRepeatReader

func NewRepeatReader(repeat byte, count int) *RepeatReader

NewRepeatReader returns a repeat reader

func (*RepeatReader) Read

func (r *RepeatReader) Read(data []byte) (int, error)

Read copies the same byte over and over to the data count times

type SlicePool

type SlicePool interface {
	// Zero zeroes slice
	Zero(b []byte)
	// Get returns a new or already allocated slice
	Get() []byte
	// Put returns slice back to the pool
	Put(b []byte)
	// Size returns a slice size
	Size() int64
}

SlicePool manages a pool of slices in attempts to manage memory in go more efficiently and avoid frequent allocations

type SliceSyncPool

type SliceSyncPool struct {
	sync.Pool
	// contains filtered or unexported fields
}

SliceSyncPool is a sync pool of slices (usually large) of the same size to optimize memory usage, see sync.Pool for more details

func NewSliceSyncPool

func NewSliceSyncPool(sliceSize int64) *SliceSyncPool

NewSliceSyncPool returns a new slice pool, using sync.Pool of pre-allocated or newly allocated slices of the predefined size and capacity

func (*SliceSyncPool) Get

func (s *SliceSyncPool) Get() []byte

Get returns a new or already allocated slice

func (*SliceSyncPool) Put

func (s *SliceSyncPool) Put(b []byte)

Put returns slice back to the pool

func (*SliceSyncPool) Size

func (s *SliceSyncPool) Size() int64

Size returns a slice size

func (*SliceSyncPool) Zero

func (s *SliceSyncPool) Zero(b []byte)

Zero zeroes slice of any length

type Stater

type Stater interface {
	// Stat returns TX, RX data.
	Stat() (uint64, uint64)
}

Stater is extension interface of the net.Conn for implementations that track connection statistics.

type SyncBuffer

type SyncBuffer struct {
	// contains filtered or unexported fields
}

SyncBuffer is in memory bytes buffer that is safe for concurrent writes

func NewSyncBuffer

func NewSyncBuffer() *SyncBuffer

NewSyncBuffer returns new in memory buffer

func (*SyncBuffer) Bytes

func (b *SyncBuffer) Bytes() []byte

Bytes returns contents of the buffer after this call, all writes will fail

func (*SyncBuffer) Close

func (b *SyncBuffer) Close() error

Close closes reads and writes on the buffer

func (*SyncBuffer) String

func (b *SyncBuffer) String() string

String returns contents of the buffer after this call, all writes will fail

func (*SyncBuffer) Write

func (b *SyncBuffer) Write(data []byte) (n int, err error)

type SyncString

type SyncString struct {
	sync.Mutex
	// contains filtered or unexported fields
}

SyncString is a string value that can be concurrently accessed

func (*SyncString) Set

func (s *SyncString) Set(v string)

Set sets the value of the string

func (*SyncString) Value

func (s *SyncString) Value() string

Value returns value of the string

type SyncWriter

type SyncWriter struct {
	io.Writer
	sync.Mutex
}

func NewSyncWriter

func NewSyncWriter(w io.Writer) *SyncWriter

func (*SyncWriter) Write

func (sw *SyncWriter) Write(b []byte) (int, error)

type TLSConn

type TLSConn interface {
	net.Conn

	// ConnectionState returns basic TLS details about the connection.
	// More info at: https://pkg.go.dev/crypto/tls#Conn.ConnectionState
	ConnectionState() tls.ConnectionState
	// Handshake runs the client or server handshake protocol if it has not yet
	// been run.
	// More info at: https://pkg.go.dev/crypto/tls#Conn.Handshake
	Handshake() error
	// HandshakeContext runs the client or server handshake protocol if it has
	// not yet been run.
	// More info at: https://pkg.go.dev/crypto/tls#Conn.HandshakeContext
	HandshakeContext(context.Context) error
}

TLSConn is a `net.Conn` that implements some of the functions defined by the `tls.Conn` struct. This interface can be used where it could receive a `tls.Conn` wrapped in another connection. For example, in the ALPN Proxy, some TLS Connections can be wrapped with ping protocol.

type TLSCredentials added in v1.0.0

type TLSCredentials struct {
	// PublicKey in PEM format
	PublicKey []byte
	// PrivateKey in PEM format
	PrivateKey []byte
	Cert       []byte
}

TLSCredentials keeps the typical 3 components of a proper HTTPS configuration

func GenerateSelfSignedCert added in v1.0.0

func GenerateSelfSignedCert(hostNames []string) (*TLSCredentials, error)

GenerateSelfSignedCert generates a self-signed certificate that is valid for given domain names and ips, returns PEM-encoded bytes with key and cert

type TextFormatter

type TextFormatter struct {
	// ComponentPadding is a padding to pick when displaying
	// and formatting component field, defaults to DefaultComponentPadding
	ComponentPadding int
	// EnableColors enables colored output
	EnableColors bool
	// FormatCaller is a function to return (part) of source file path for output.
	// Defaults to filePathAndLine() if unspecified
	FormatCaller func() (caller string)
	// ExtraFields represent the extra fields that will be added to the log message
	ExtraFields []string
	// contains filtered or unexported fields
}

func NewDefaultTextFormatter

func NewDefaultTextFormatter(enableColors bool) *TextFormatter

func (*TextFormatter) CheckAndSetDefaults

func (tf *TextFormatter) CheckAndSetDefaults() error

CheckAndSetDefaults checks and sets log format configuration

func (*TextFormatter) Format

func (tf *TextFormatter) Format(e *log.Entry) ([]byte, error)

Format formats each log line as configured in teleport config file

type TimedCounter

type TimedCounter struct {
	// contains filtered or unexported fields
}

TimedCounter is essentially a lightweight rate calculator. It counts events that happen over a period of time, e.g. have there been more than 4 errors in the last 30 seconds. Automatically expires old events so they are not included in the count. Not safe for concurrent use.

func NewTimedCounter

func NewTimedCounter(clock clockwork.Clock, timeout time.Duration) *TimedCounter

NewTimedCounter creates a new timed counter with the specified timeout

func (*TimedCounter) Count

func (c *TimedCounter) Count() int

Count fetches the number of recorded events currently in the measurement time window.

func (*TimedCounter) Increment

func (c *TimedCounter) Increment() int

Increment adds a new item into the counter, returning the current count.

type TimeoutConn added in v1.2.6

type TimeoutConn struct {
	net.Conn
	TimeoutDuration time.Duration

	// Name is only useful for debugging/logging, it's a convenient
	// way to tag every idle connection
	OwnerName string
}

TimeoutConn wraps an existing net.Conn and adds read/write timeouts for it, allowing to implement "disconnect after XX of idle time" policy

Usage example: tc := utils.ObeyIdleTimeout(conn, time.Second * 30, "ssh connection") io.Copy(tc, xxx)

func (*TimeoutConn) Read added in v1.2.6

func (tc *TimeoutConn) Read(p []byte) (n int, err error)

func (*TimeoutConn) Write added in v1.2.6

func (tc *TimeoutConn) Write(p []byte) (n int, err error)

type Tracer

type Tracer struct {
	// Started records starting time of the call
	Started time.Time
	// Description is arbitrary description
	Description string
}

Tracer helps to trace execution of functions

func NewTracer

func NewTracer(description string) *Tracer

NewTracer returns a new tracer

func (*Tracer) Start

func (t *Tracer) Start() *Tracer

Start logs start of the trace

func (*Tracer) Stop

func (t *Tracer) Stop() *Tracer

Stop logs stop of the trace

type TrackingConn

type TrackingConn struct {
	// net.Conn is the underlying net.Conn.
	net.Conn
	// contains filtered or unexported fields
}

TrackingConn is a net.Conn that keeps track of how much data was transmitted (TX) and received (RX) over the net.Conn. A maximum of about 18446 petabytes can be kept track of for TX and RX before it rolls over. See https://golang.org/ref/spec#Numeric_types for more details.

func NewTrackingConn

func NewTrackingConn(conn net.Conn) *TrackingConn

NewTrackingConn returns a net.Conn that can keep track of how much data was transmitted over it.

func (*TrackingConn) Read

func (s *TrackingConn) Read(b []byte) (n int, err error)

func (*TrackingConn) Stat

func (s *TrackingConn) Stat() (uint64, uint64)

Stat returns the transmitted (TX) and received (RX) bytes over the net.Conn.

func (*TrackingConn) Write

func (s *TrackingConn) Write(b []byte) (n int, err error)

type TrackingReader

type TrackingReader struct {
	// contains filtered or unexported fields
}

TrackingReader is an io.Reader that counts the total number of bytes read. It's thread-safe if the underlying io.Reader is thread-safe.

func NewTrackingReader

func NewTrackingReader(r io.Reader) *TrackingReader

NewTrackingReader creates a TrackingReader around r.

func (*TrackingReader) Count

func (r *TrackingReader) Count() uint64

Count returns the total number of bytes read so far.

func (*TrackingReader) Read

func (r *TrackingReader) Read(b []byte) (int, error)

type TrackingWriter

type TrackingWriter struct {
	// contains filtered or unexported fields
}

TrackingWriter is an io.Writer that counts the total number of bytes written. It's thread-safe if the underlying io.Writer is thread-safe.

func NewTrackingWriter

func NewTrackingWriter(w io.Writer) *TrackingWriter

NewTrackingWriter creates a TrackingWriter around w.

func (*TrackingWriter) Count

func (w *TrackingWriter) Count() uint64

Count returns the total number of bytes written so far.

func (*TrackingWriter) Write

func (w *TrackingWriter) Write(b []byte) (int, error)

type UID

type UID interface {
	// New returns a new UUID4.
	New() string
}

UID provides an interface for generating unique identifiers.

func NewFakeUID

func NewFakeUID() UID

NewFakeUID returns a new fake UID generator used in tests.

func NewRealUID

func NewRealUID() UID

NewRealUID returns a new real UID generator.

type WebLinks struct {
	// NextPage is the next page of pagination links.
	NextPage string

	// PrevPage is the previous page of pagination links.
	PrevPage string

	// FirstPage is the first page of pagination links.
	FirstPage string

	// LastPage is the last page of pagination links.
	LastPage string
}

WebLinks holds the pagination links parsed out of a request header conforming to RFC 8288.

func ParseWebLinks(response *http.Response) WebLinks

ParseWebLinks partially implements RFC 8288 parsing, enough to support GitHub pagination links. See https://tools.ietf.org/html/rfc8288 for more details on Web Linking and https://github.com/google/go-github for the API client that this function was original extracted from.

Link headers typically look like:

Link: <https://api.github.com/user/teams?page=2>; rel="next",
  <https://api.github.com/user/teams?page=34>; rel="last"

type WriteContextCloser

type WriteContextCloser interface {
	Close(ctx context.Context) error
	io.Writer
}

WriteContextCloser provides close method with context

Directories

Path Synopsis
TODO(awly): combine Expression and Matcher.
TODO(awly): combine Expression and Matcher.
Package prompt implements CLI prompts to the user.
Package prompt implements CLI prompts to the user.
package socks implements a SOCKS5 handshake.
package socks implements a SOCKS5 handshake.
Package workpool provies the `Pool` type which functions as a means of managing the number of concurrent workers, grouped by key.
Package workpool provies the `Pool` type which functions as a means of managing the number of concurrent workers, grouped by key.

Jump to

Keyboard shortcuts

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