utils

package
v0.0.0-...-8d1852a Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2022 License: Apache-2.0 Imports: 36 Imported by: 0

Documentation

Overview

Copyright 2015 Gravitational, Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2015 Gravitational, Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2015 Gravitational, Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

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 (
	// CertTeleportUser specifies teleport user
	CertTeleportUser = "x-teleport-user"
	// 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"
)
View Source
const (
	WebSocketBinaryMode = iota
	WebSocketTextMode
)

Variables

This section is empty.

Functions

func Consolef

func Consolef(w io.Writer, msg string, params ...interface{})

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

func CreateTLSConfiguration

func CreateTLSConfiguration(certFile, keyFile string) (*tls.Config, error)

CreateTLSConfiguration sets up default TLS configuration

func CryptoRandomHex

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 FatalError

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 GetLoginShell

func GetLoginShell(username string) (string, error)

GetLoginShell determines the login shell for a given username

func GuessHostIP

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 InitCLIParser

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 InitDebugLogger

func InitDebugLogger(level log.Level)

func InitLoggerCLI

func InitLoggerCLI()

InitLoggerCLI tools by default log into syslog, not stderr

func InitLoggerDebug

func InitLoggerDebug()

InitLoggerDebug configures the logger to dump everything to stderr

func InitLoggerForTests

func InitLoggerForTests()

InitLoggerForTests inits logger to discard ouput in tests unless TELEPORT_DEBUG is set to "true"

func InitLoggerVerbose

func InitLoggerVerbose()

InitLoggerVerbose is a less chatty version of debug logger above

func IsDir

func IsDir(dirPath string) bool

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

func IsFile

func IsFile(fp string) bool

IsFile returns true if a given file path points to an existing file

func IsHandshakeFailedError

func IsHandshakeFailedError(err error) bool

IsHandshakeFailedError specifies whether this error indicates failed handshake

func IsLocalhost

func IsLocalhost(host string) bool

IsLocalhost returns true if this is a local hostname or ip

func IsLoopback

func IsLoopback(host string) bool

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

func IsShellFailedError

func IsShellFailedError(err error) bool

IsShellFailedError specifies whether this error indicates failed attempt to start shell

func ListenTLS

func ListenTLS(address string, certFile, keyFile string) (net.Listener, error)

ListenTLS sets up TLS listener for the http handler, starts listening on a TCP socket and returns the socket which is ready to be used for http.Serve

func MultiCloser

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

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

func NewChConn

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

func ObeyTimeouts

func ObeyTimeouts(conn net.Conn, timeout time.Duration, name string) net.Conn

ObeyTimeouts wraps an existing network connection with timeout-obeying Write() and Read()

func ObjectToStruct

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

func PrintVersion

func PrintVersion()

PrintVersion prints human readable version

func RandomDuration

func RandomDuration(max time.Duration) time.Duration

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

func ReadAll

func ReadAll(r io.Reader, bufsize int) (out []byte, err error)

ReadAll is similarl to ioutil.ReadAll, except it doesn't use ever-increasing internal buffer, instead asking for the exact buffer size.

This is useful when you want to limit the sze of Read/Writes (websockets)

func ReadHostUUID

func ReadHostUUID(dataDir string) (string, error)

ReadHostUUID reads host UUID from the file in the data dir

func ReadOrMakeHostUUID

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)

func ReplaceLocalhost

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 SliceContainsStr

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

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

func SplitReaders

func SplitReaders(r1 io.Reader, r2 io.Reader) io.Reader

func StartHTTPServer

func StartHTTPServer(addr NetAddr, h http.Handler) error

func UserMessageFromError

func UserMessageFromError(err error) string

UserMessageFromError returns user friendly error message from error

func WriteHostUUID

func WriteHostUUID(dataDir string, id string) error

WriteHostUUID writes host UUID into a file

Types

type AddrStorage

type AddrStorage interface {
	// SetAddresses saves addresses
	SetAddresses([]NetAddr) error
	// GetAddresses
	GetAddresses() ([]NetAddr, error)
}

AddrStorage is used to store information locally for every client that connects in the cluster, so it can always have up-to-date info about auth servers

type CloseBroadcaster

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

func NewCloseBroadcaster() *CloseBroadcaster

NewCloseBroadcaster returns new instance of close broadcaster

func (*CloseBroadcaster) Close

func (b *CloseBroadcaster) Close() error

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

type FileAddrStorage

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

FileAddrStorage is a file based address storage

func NewFileAddrStorage

func NewFileAddrStorage(filePath string) *FileAddrStorage

NewFileAddrStorage returns new instance of file-based address storage

func (*FileAddrStorage) GetAddresses

func (fs *FileAddrStorage) GetAddresses() ([]NetAddr, error)

GetAddresses returns saved address list

func (*FileAddrStorage) SetAddresses

func (fs *FileAddrStorage) SetAddresses(addrs []NetAddr) error

SetAddresses updates storage with new address list

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 HostKeyCallback

type HostKeyCallback func(hostID string, remote net.Addr, key ssh.PublicKey) error

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 MustParseAddr

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 ParseHostPortAddr

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

func (a *NetAddr) IsEmpty() bool

IsEmpty returns true if address is empty

func (*NetAddr) IsLocal

func (a *NetAddr) IsLocal() bool

IsLocal returns true if this is a local address

func (*NetAddr) IsLoopback

func (a *NetAddr) IsLoopback() bool

IsLoopback returns true if this is a loopback address

func (*NetAddr) MarshalYAML

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

type NetAddrList []NetAddr

NetAddrList is a list of NetAddrs that supports helper methods for parsing from CLI tools

func (*NetAddrList) Addresses

func (nl *NetAddrList) Addresses() []string

Addresses returns a slice of strings converted from the addresses

func (*NetAddrList) Set

func (nl *NetAddrList) Set(s string) error

Set is called by CLI tools

func (*NetAddrList) String

func (nl *NetAddrList) String() string

String returns debug-friendly representation of the tool

type NetAddrVal

type NetAddrVal NetAddr

NetAddrVal can be used with flag package

func NewNetAddrVal

func NewNetAddrVal(defaultVal NetAddr, val *NetAddr) *NetAddrVal

func (*NetAddrVal) Get

func (a *NetAddrVal) Get() interface{}

func (*NetAddrVal) Set

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

func (*NetAddrVal) String

func (a *NetAddrVal) String() string

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

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

type PortList []string

PortList is a list of TCP port

func GetFreeTCPPorts

func GetFreeTCPPorts(n int) (PortList, error)

GetFreeTCPPorts returns a lit of available ports on localhost used for testing

func (*PortList) Pop

func (p *PortList) Pop() string

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

type TLSCredentials

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

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

type TimeoutConn struct {
	net.Conn
	TimeoutDuration time.Duration

	// Name is only useful for debugging/logging, it's a convenient
	// way to "name" every active connection
	Name string
}

TimeoutConn wraps an existing net.Conn and adds read/write timeouts for it, allowing to safely pass it into io.Copy()

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

func (*TimeoutConn) Read

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

func (*TimeoutConn) Write

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

type WebSockWrapper

type WebSockWrapper struct {
	io.ReadWriteCloser
	// contains filtered or unexported fields
}

WebSockWrapper wraps the raw websocket and converts Write() calls to proper websocket.Send() working in binary or text mode. If text mode is selected, it converts the data passed to Write() into UTF8 bytes

We need this to make sure that the entire buffer in io.Writer.Write(buffer) is delivered as a single chunk to the web browser, instead of being split into multiple frames. This wrapper basically substitues every Write() with Send() and every Read() with Receive()

func NewWebSockWrapper

func NewWebSockWrapper(ws *websocket.Conn, m WebSocketMode) *WebSockWrapper

func (*WebSockWrapper) Close

func (w *WebSockWrapper) Close() error

func (*WebSockWrapper) Read

func (w *WebSockWrapper) Read(out []byte) (n int, err error)

Read does the opposite of write: it replaces websocket's raw "Read" with

It replaces raw Read() with "Message.Receive()"

func (*WebSockWrapper) Write

func (w *WebSockWrapper) Write(data []byte) (n int, err error)

Write implements io.WriteCloser for WebSockWriter (that's the reason we're wrapping the websocket)

It replaces raw Write() with "Message.Send()"

type WebSocketMode

type WebSocketMode int

WebSocketMode allows to create WebSocket wrappers working in text or binary mode

Jump to

Keyboard shortcuts

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