utils

package
v4.3.6-dev.3+incompatible Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2020 License: Apache-2.0 Imports: 60 Imported by: 0

Documentation

Index

Constants

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 (
	// HumanTimeFormatString is a human readable date formatting
	HumanTimeFormatString = "Mon Jan _2 15:04 UTC"
	// 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"
)
View Source
const (
	// ConnectionTypeRequest is a request sent over a SSH channel that returns a
	// boolean which indicates the connection type (direct or tunnel).
	ConnectionTypeRequest = "x-teleport-connection-type"
)
View Source
const PortStartingNumber = 20000

PortStartingNumber is a starting port number for tests

Variables

This section is empty.

Functions

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 Capitalize

func Capitalize(s string) string

Capitalize returns a copy of the string with first rune converted to capital letter

func CheckCertificateFormatFlag

func CheckCertificateFormatFlag(s string) (string, error)

CheckCertificateFormatFlag checks if the certificate format is valid.

func CheckSPKI

func CheckSPKI(pin string, cert *x509.Certificate) error

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

func CheckVersions

func CheckVersions(clientVersion string, minClientVersion string) error

CheckVersions compares client and server versions and makes sure that the client version is greater than or equal to the minimum version supported by the server.

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 Consolef added in v1.0.0

func Consolef(w io.Writer, component string, 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 CopyByteSlice

func CopyByteSlice(in []byte) []byte

CopyByteSlice returns a copy of the byte slice.

func CopyByteSlices

func CopyByteSlices(in [][]byte) [][]byte

CopyByteSlices returns a copy of the byte slices.

func CopyStrings

func CopyStrings(in []string) []string

CopyStrings makes a deep copy of the passed in string slice and returns the copy.

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(len int) (string, error)

CryptoRandomHex returns hex encoded random string generated with crypto-strong pseudo random generator of the given bytes

func Deduplicate

func Deduplicate(in []string) []string

Deduplicate deduplicates list of strings

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 FSReadLock

func FSReadLock(f *os.File) error

FSReadLock grabs Flock-style filesystem lock on an open file in read (shared) mode

func FSTryWriteLock

func FSTryWriteLock(f *os.File) error

FSTryWriteLock tries to grab write lock, returns CompareFailed if lock is already grabbed

func FSUnlock

func FSUnlock(f *os.File) error

FSUnlock unlcocks Flock-style filesystem lock

func FSWriteLock

func FSWriteLock(f *os.File) error

FSWriteLock grabs Flock-style filesystem lock on an open file in exclusive mode.

func FastMarshal

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

FastMarshal uses the json-iterator library for fast JSON marshalling. Note, this function marshals 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 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 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 Host

func Host(hostname string) (string, error)

Host extracts host from host:port string

func HumanTimeFormat

func HumanTimeFormat(d time.Time) string

HumanTimeFormat formats time as recognized by humans

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 log.Level, verbose ...bool)

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

func InitLoggerForTests added in v1.0.0

func InitLoggerForTests(verbose ...bool)

func IsCertExpiredError

func IsCertExpiredError(err error) bool

IsCertExpiredError specifies whether this error indicates expired SSH certificate

func IsDir added in v1.0.0

func IsDir(dirPath string) bool

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

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 IsLoopback added in v1.0.0

func IsLoopback(host string) bool

IsLoopback returns 'true' if a given hostname resolves to local host's loopback interface

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 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 MinTTL

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

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

func MkdirAll

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

MkdirAll creates directory and subdirectories

func MultiCloser

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

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

func NewHMACAnonymizer

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

NewHMACAnonymizer returns a new HMAC-based anonymizer

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 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 ObjectToStruct

func ObjectToStruct(in interface{}, out interface{}) error

ObjectToStruct is converts any structure into JSON and then unmarshalls it into another structure.

Teleport configuration uses this (strange, at first) trick to convert from one struct type to another, if their fields are loosely compatible via their `json` tags

Example: assume you have two structs:

type A struct {
    Name string `json:"name"`
	   Age  int    `json:"age"`
}
type B struct {
	   FullName string `json:"name"`
}

Now you can convert B to A:

		b := &B{ FullName: "Bob Dilan"}
		var a *A
		utils.ObjectToStruct(b, &a)
		fmt.Println(a.Name)

 > "Bob Dilan"

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 ParseBool

func ParseBool(value string) (bool, error)

ParseBool parses string as boolean value, returns error in case if value is not recognized

func ParseCertificatePEM

func ParseCertificatePEM(bytes []byte) (*x509.Certificate, error)

ParseCertificatePEM parses PEM-encoded certificate

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 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 ParseSessionsURI

func ParseSessionsURI(in string) (*url.URL, error)

ParseSessionsURI parses uri per convention of session upload URIs file is a default scheme

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 RandomDuration added in v1.0.0

func RandomDuration(max time.Duration) time.Duration

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

func ReadCertificateChain

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

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

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 ReadToken

func ReadToken(token string) (string, error)

ReadToken is a utility function to read the token from the disk if it looks like a path, otherwise, treat it as a value

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 not found error

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 SliceContainsStr

func SliceContainsStr(slice []string, value string) bool

SliceContainsStr returns 'true' if the slice contains the given value

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 StatDir

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

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

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 StringSlicesEqual

func StringSlicesEqual(a, b []string) bool

StringSlicesEqual returns true if string slices equal

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 SwitchLoggingtoSyslog

func SwitchLoggingtoSyslog() error

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

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 UTC

func UTC(t *time.Time)

UTC converts time to UTC timezone

func UintSliceSubset

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

UintSliceSubset returns true if b is a subset of a.

func UnmarshalWithSchema

func UnmarshalWithSchema(schemaDefinition string, object interface{}, data []byte) error

UnmarshalWithSchema processes YAML or JSON encoded object with JSON schema, sets defaults and unmarshals resulting object into given struct

func UserMessageFromError added in v1.0.0

func UserMessageFromError(err error) string

UserMessageFromError returns user friendly error message from error

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 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 BroadcastWriter

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

BroadcastWriter broadcasts all writes to all writers

func NewBroadcastWriter

func NewBroadcastWriter(writers ...io.Writer) *BroadcastWriter

NewBroadcastWriter returns new broadcast writer

func (*BroadcastWriter) Write

func (w *BroadcastWriter) Write(p []byte) (n int, err error)

Write multiplexes the input to multiple sub-writers. If any of the write fails, it won't attempt to write to other writers

type CertChecker

type CertChecker struct {
	ssh.CertChecker

	// FIPS means in addition to checking the validity of the key or
	// certificate, also check that FIPS 140-2 algorithms were used.
	FIPS bool
}

CertChecker is a drop-in replacement for ssh.CertChecker. In FIPS mode, checks if the certificate (or key) were generated with a supported algorithm.

func (*CertChecker) Authenticate

func (c *CertChecker) Authenticate(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error)

Authenticate checks the validity of a user certificate.

func (*CertChecker) CheckCert

func (c *CertChecker) CheckCert(principal string, cert *ssh.Certificate) error

CheckCert checks certificate metadata and signature.

func (*CertChecker) CheckHostKey

func (c *CertChecker) CheckHostKey(addr string, remote net.Addr, key ssh.PublicKey) error

CheckHostKey checks the validity of a host certificate.

type ChConn

type ChConn struct {
	ssh.Channel
	// contains filtered or unexported fields
}

ChConn is a net.Conn like object that uses SSH channel

func NewChConn added in v1.0.0

func NewChConn(conn ssh.Conn, ch ssh.Channel) *ChConn

NewChConn returns a new net.Conn implemented over SSH channel

func NewExclusiveChConn

func NewExclusiveChConn(conn ssh.Conn, ch ssh.Channel) *ChConn

NewExclusiveChConn returns a new net.Conn implemented over SSH channel, whenever this connection closes

func (*ChConn) Close

func (c *ChConn) Close() error

Close closes channel and if the ChConn is exclusive, connection as well

func (*ChConn) LocalAddr

func (c *ChConn) LocalAddr() net.Addr

LocalAddr returns a local address of a connection Uses underlying net.Conn implementation

func (*ChConn) RemoteAddr

func (c *ChConn) RemoteAddr() net.Addr

RemoteAddr returns a remote address of a connection Uses underlying net.Conn implementation

func (*ChConn) SetDeadline

func (c *ChConn) SetDeadline(t time.Time) error

SetDeadline sets a connection deadline ignored for the channel connection

func (*ChConn) SetReadDeadline

func (c *ChConn) SetReadDeadline(t time.Time) error

SetReadDeadline sets a connection read deadline ignored for the channel connection

func (*ChConn) SetWriteDeadline

func (c *ChConn) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets write deadline on a connection ignored for the channel connection

func (*ChConn) UseTunnel

func (c *ChConn) UseTunnel() bool

UseTunnel makes a channel request asking for the type of connection. If the other side does not respond (older cluster) or takes to long to respond, be on the safe side and assume it's not a tunnel connection.

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 DialWithContextFunc

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

DialWithContext dials with context

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 Jitter

type Jitter func(time.Duration) time.Duration

Jitter is a function which applies random jitter to a duration. Used to randomize backoff values. Must be safe for concurrent usage.

func NewJitter

func NewJitter() Jitter

NewJitter returns the default jitter (currently jitters on the range [n/2,n), but this is subject to change).

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 Linear

type Linear struct {
	// LinearConfig is a linear retry config
	LinearConfig
	// contains filtered or unexported fields
}

Linear is used to calculate retry period that follows the following logic: On the first error there is no delay on the next error, delay is FastLinear on all other errors, delay is SlowLinear

func NewLinear

func NewLinear(cfg LinearConfig) (*Linear, error)

NewLinear returns a new instance of linear retry

func (*Linear) After

func (r *Linear) After() <-chan time.Time

After returns channel that fires with timeout defined in Duration method, as a special case if Duration is 0 returns a closed channel

func (*Linear) Clone

func (r *Linear) Clone() Retry

Clone creates an identical copy of Linear with fresh state.

func (*Linear) Duration

func (r *Linear) Duration() time.Duration

Duration returns retry duration based on state

func (*Linear) Inc

func (r *Linear) Inc()

Inc increments attempt counter

func (*Linear) Reset

func (r *Linear) Reset()

Reset resetes retry period to initial state

func (*Linear) String

func (r *Linear) String() string

String returns user-friendly representation of the LinearPeriod

type LinearConfig

type LinearConfig struct {
	// First is a first element of the progression,
	// could be 0
	First time.Duration
	// Step is a step of the progression, can't be 0
	Step time.Duration
	// Max is a maximum value of the progression,
	// can't be 0
	Max time.Duration
	// Jitter is an optional jitter function to be applied
	// to the delay.  Note that supplying a jitter means that
	// successive calls to Duration may return different results.
	Jitter Jitter
	// AutoReset, if greater than zero, causes the linear retry to automatically
	// reset after Max * AutoReset has elapsed since the last call to Incr.
	AutoReset int64
}

LinearConfig sets up retry configuration using arithmetic progression

func (*LinearConfig) CheckAndSetDefaults

func (c *LinearConfig) CheckAndSetDefaults() error

CheckAndSetDefaults checks and sets defaults

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 (*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 LoggingPurpose

type LoggingPurpose int
const (
	LoggingForDaemon LoggingPurpose = iota
	LoggingForCLI
	LoggingForTests
)

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 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 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) Equals

func (a *NetAddr) Equals(other NetAddr) bool

Equals returns true if address is equal to other

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) 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 marshalled 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 PipeNetConn

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

PipeNetConn implemetns net.Conn from 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 returns a net.Conn like object using Pipe as an underlying implementation over reader, writer and 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 []string

PortList is a list of TCP port

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 RemoveDirCloser

type RemoveDirCloser struct {
	Path string
}

RemoveDirCloser removes directory and all it's contents when Close is called

func (*RemoveDirCloser) Close

func (r *RemoveDirCloser) Close() error

Close removes directory and all it's contents

type Retry

type Retry interface {
	// Reset resets retry state
	Reset()
	// Inc increments retry attempt
	Inc()
	// Duration returns retry duration,
	// could be 0
	Duration() time.Duration
	// After returns time.Time channel
	// that fires after Duration delay,
	// could fire right away if Duration is 0
	After() <-chan time.Time
	// Clone creates a copy of this retry in a
	// reset state.
	Clone() Retry
}

Retry is an interface that provides retry logic

type SigningKeyStore

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

SigningKeyStore is used to sign using X509 digital signatures

func ParseSigningKeyStorePEM

func ParseSigningKeyStorePEM(keyPEM, certPEM string) (*SigningKeyStore, error)

ParseSigningKeyStore parses signing key store from PEM encoded key pair

func (*SigningKeyStore) GetKeyPair

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

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 Strings

type Strings []string

Strings is a list of string that can unmarshal from list of strings or a scalar string from scalar yaml or json property

func (Strings) Addrs

func (s Strings) Addrs(defaultPort int) ([]NetAddr, error)

Addrs returns strings list converted to address list

func (Strings) MarshalJSON

func (s Strings) MarshalJSON() ([]byte, error)

MarshalJSON marshals to scalar value if there is only one value in the list to list otherwise

func (Strings) MarshalYAML

func (s Strings) MarshalYAML() (interface{}, error)

MarshalYAML marshals to scalar value if there is only one value in the list, marshals to list otherwise

func (*Strings) UnmarshalJSON

func (s *Strings) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals scalar string or strings slice to Strings

func (*Strings) UnmarshalYAML

func (s *Strings) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML is used to allow Strings to unmarshal from scalar string value or from the list

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 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 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 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"

Directories

Path Synopsis
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