repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/authhandlers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L385-L427
go
train
// authorityForCert checks if the certificate was signed by a Teleport // Certificate Authority and returns it.
func (h *AuthHandlers) authorityForCert(caType services.CertAuthType, key ssh.PublicKey) (services.CertAuthority, error)
// authorityForCert checks if the certificate was signed by a Teleport // Certificate Authority and returns it. func (h *AuthHandlers) authorityForCert(caType services.CertAuthType, key ssh.PublicKey) (services.CertAuthority, error)
{ // get all certificate authorities for given type cas, err := h.AccessPoint.GetCertAuthorities(caType, false) if err != nil { h.Warnf("%v", trace.DebugReport(err)) return nil, trace.Wrap(err) } // find the one that signed our certificate var ca services.CertAuthority for i := range cas { checkers, err ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/authhandlers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L430-L435
go
train
// isProxy returns true if it's a regular SSH proxy.
func (h *AuthHandlers) isProxy() bool
// isProxy returns true if it's a regular SSH proxy. func (h *AuthHandlers) isProxy() bool
{ if h.Component == teleport.ComponentProxy { return true } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/authhandlers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L446-L453
go
train
// extractRolesFromCert extracts roles from certificate metadata extensions.
func extractRolesFromCert(cert *ssh.Certificate) ([]string, error)
// extractRolesFromCert extracts roles from certificate metadata extensions. func extractRolesFromCert(cert *ssh.Certificate) ([]string, error)
{ data, ok := cert.Extensions[teleport.CertExtensionTeleportRoles] if !ok { // it's ok to not have any roles in the metadata return nil, nil } return services.UnmarshalCertRoles(data) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/sessions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L116-L154
go
train
// GetUserClient will return an auth.ClientI with the role of the user at // the requested site. If the site is local a client with the users local role // is returned. If the site is remote a client with the users remote role is // returned.
func (c *SessionContext) GetUserClient(site reversetunnel.RemoteSite) (auth.ClientI, error)
// GetUserClient will return an auth.ClientI with the role of the user at // the requested site. If the site is local a client with the users local role // is returned. If the site is remote a client with the users remote role is // returned. func (c *SessionContext) GetUserClient(site reversetunnel.RemoteSite) (auth.C...
{ // get the name of the current cluster clt, err := c.GetClient() if err != nil { return nil, trace.Wrap(err) } cn, err := clt.GetClusterName() if err != nil { return nil, trace.Wrap(err) } // if we're trying to access the local cluster, pass back the local client. if cn.GetClusterName() == site.GetName...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/sessions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L158-L164
go
train
// newRemoteClient returns a client to a remote cluster with the role of // the logged in user.
func (c *SessionContext) newRemoteClient(cluster reversetunnel.RemoteSite) (auth.ClientI, net.Conn, error)
// newRemoteClient returns a client to a remote cluster with the role of // the logged in user. func (c *SessionContext) newRemoteClient(cluster reversetunnel.RemoteSite) (auth.ClientI, net.Conn, error)
{ clt, err := c.tryRemoteTLSClient(cluster) if err != nil { return nil, nil, trace.Wrap(err) } return clt, nil, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/sessions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L167-L171
go
train
// clusterDialer returns DialContext function using cluster's dial function
func clusterDialer(remoteCluster reversetunnel.RemoteSite) auth.DialContext
// clusterDialer returns DialContext function using cluster's dial function func clusterDialer(remoteCluster reversetunnel.RemoteSite) auth.DialContext
{ return func(in context.Context, network, _ string) (net.Conn, error) { return remoteCluster.DialAuthServer() } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/sessions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L175-L185
go
train
// tryRemoteTLSClient tries creating TLS client and using it (the client may not be available // due to older clusters), returns client if it is working properly
func (c *SessionContext) tryRemoteTLSClient(cluster reversetunnel.RemoteSite) (auth.ClientI, error)
// tryRemoteTLSClient tries creating TLS client and using it (the client may not be available // due to older clusters), returns client if it is working properly func (c *SessionContext) tryRemoteTLSClient(cluster reversetunnel.RemoteSite) (auth.ClientI, error)
{ clt, err := c.newRemoteTLSClient(cluster) if err != nil { return nil, trace.Wrap(err) } _, err = clt.GetDomainName() if err != nil { return clt, trace.Wrap(err) } return clt, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/sessions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L189-L223
go
train
// ClientTLSConfig returns client TLS authentication associated // with the web session context
func (c *SessionContext) ClientTLSConfig(clusterName ...string) (*tls.Config, error)
// ClientTLSConfig returns client TLS authentication associated // with the web session context func (c *SessionContext) ClientTLSConfig(clusterName ...string) (*tls.Config, error)
{ var certPool *x509.CertPool if len(clusterName) == 0 { certAuthorities, err := c.parent.proxyClient.GetCertAuthorities(services.HostCA, false) if err != nil { return nil, trace.Wrap(err) } certPool, err = services.CertPoolFromCertAuthorities(certAuthorities) if err != nil { return nil, trace.Wrap(e...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/sessions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L245-L251
go
train
// ExtendWebSession creates a new web session for this user // based on the previous session
func (c *SessionContext) ExtendWebSession() (services.WebSession, error)
// ExtendWebSession creates a new web session for this user // based on the previous session func (c *SessionContext) ExtendWebSession() (services.WebSession, error)
{ sess, err := c.clt.ExtendWebSession(c.user, c.sess.GetName()) if err != nil { return nil, trace.Wrap(err) } return sess, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/sessions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L255-L281
go
train
// GetAgent returns agent that can be used to answer challenges // for the web to ssh connection as well as certificate
func (c *SessionContext) GetAgent() (agent.Agent, *ssh.Certificate, error)
// GetAgent returns agent that can be used to answer challenges // for the web to ssh connection as well as certificate func (c *SessionContext) GetAgent() (agent.Agent, *ssh.Certificate, error)
{ pub, _, _, _, err := ssh.ParseAuthorizedKey(c.sess.GetPub()) if err != nil { return nil, nil, trace.Wrap(err) } cert, ok := pub.(*ssh.Certificate) if !ok { return nil, nil, trace.BadParameter("expected certificate, got %T", pub) } if len(cert.ValidPrincipals) == 0 { return nil, nil, trace.BadParameter("...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/sessions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L284-L294
go
train
// Close cleans up connections associated with requests
func (c *SessionContext) Close() error
// Close cleans up connections associated with requests func (c *SessionContext) Close() error
{ closers := c.TransferClosers() for _, closer := range closers { c.Debugf("Closing %v.", closer) closer.Close() } if c.clt != nil { return trace.Wrap(c.clt.Close()) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/sessions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L297-L317
go
train
// newSessionCache returns new instance of the session cache
func newSessionCache(proxyClient auth.ClientI, servers []utils.NetAddr, cipherSuites []uint16) (*sessionCache, error)
// newSessionCache returns new instance of the session cache func newSessionCache(proxyClient auth.ClientI, servers []utils.NetAddr, cipherSuites []uint16) (*sessionCache, error)
{ clusterName, err := proxyClient.GetClusterName() if err != nil { return nil, trace.Wrap(err) } m, err := ttlmap.New(1024, ttlmap.CallOnExpire(closeContext)) if err != nil { return nil, trace.Wrap(err) } cache := &sessionCache{ clusterName: clusterName.GetClusterName(), proxyClient: proxyClient, co...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/sessions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L341-L353
go
train
// closeContext is called when session context expires from // cache and will clean up connections
func closeContext(key string, val interface{})
// closeContext is called when session context expires from // cache and will clean up connections func closeContext(key string, val interface{})
{ go func() { log.Infof("[WEB] closing context %v", key) ctx, ok := val.(*SessionContext) if !ok { log.Warningf("warning, not valid value type %T", val) return } if err := ctx.Close(); err != nil { log.Infof("failed to close context: %v", err) } }() }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/github.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/github.go#L40-L62
go
train
// CreateGithubAuthRequest creates a new request for Github OAuth2 flow
func (s *AuthServer) CreateGithubAuthRequest(req services.GithubAuthRequest) (*services.GithubAuthRequest, error)
// CreateGithubAuthRequest creates a new request for Github OAuth2 flow func (s *AuthServer) CreateGithubAuthRequest(req services.GithubAuthRequest) (*services.GithubAuthRequest, error)
{ connector, err := s.Identity.GetGithubConnector(req.ConnectorID, true) if err != nil { return nil, trace.Wrap(err) } client, err := s.getGithubOAuth2Client(connector) if err != nil { return nil, trace.Wrap(err) } req.StateToken, err = utils.CryptoRandomHex(TokenLenBytes) if err != nil { return nil, tra...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/github.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/github.go#L84-L100
go
train
// ValidateGithubAuthCallback validates Github auth callback redirect
func (a *AuthServer) ValidateGithubAuthCallback(q url.Values) (*GithubAuthResponse, error)
// ValidateGithubAuthCallback validates Github auth callback redirect func (a *AuthServer) ValidateGithubAuthCallback(q url.Values) (*GithubAuthResponse, error)
{ re, err := a.validateGithubAuthCallback(q) if err != nil { a.EmitAuditEvent(events.UserSSOLoginFailure, events.EventFields{ events.LoginMethod: events.LoginMethodGithub, events.AuthAttemptSuccess: false, events.AuthAttemptErr: err.Error(), }) } else { a.EmitAuditEvent(events.UserSSOLogin...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/github.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/github.go#L103-L213
go
train
// ValidateGithubAuthCallback validates Github auth callback redirect
func (s *AuthServer) validateGithubAuthCallback(q url.Values) (*GithubAuthResponse, error)
// ValidateGithubAuthCallback validates Github auth callback redirect func (s *AuthServer) validateGithubAuthCallback(q url.Values) (*GithubAuthResponse, error)
{ logger := log.WithFields(logrus.Fields{trace.Component: "github"}) error := q.Get("error") if error != "" { return nil, trace.OAuth2(oauth2.ErrorInvalidRequest, error, q) } code := q.Get("code") if code == "" { return nil, trace.OAuth2(oauth2.ErrorInvalidRequest, "code query param must be set", q) } s...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/github.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/github.go#L366-L395
go
train
// populateGithubClaims retrieves information about user and its team // memberships by calling Github API using the access token
func populateGithubClaims(client githubAPIClientI) (*services.GithubClaims, error)
// populateGithubClaims retrieves information about user and its team // memberships by calling Github API using the access token func populateGithubClaims(client githubAPIClientI) (*services.GithubClaims, error)
{ // find out the username user, err := client.getUser() if err != nil { return nil, trace.Wrap(err, "failed to query Github user info") } // build team memberships teams, err := client.getTeams() if err != nil { return nil, trace.Wrap(err, "failed to query Github user teams") } log.Debugf("Retrieved %v t...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/github.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/github.go#L450-L462
go
train
// getEmails retrieves a list of emails for authenticated user
func (c *githubAPIClient) getUser() (*userResponse, error)
// getEmails retrieves a list of emails for authenticated user func (c *githubAPIClient) getUser() (*userResponse, error)
{ // Ignore pagination links, we should never get more than a single user here. bytes, _, err := c.get("/user") if err != nil { return nil, trace.Wrap(err) } var user userResponse err = json.Unmarshal(bytes, &user) if err != nil { return nil, trace.Wrap(err) } return &user, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/github.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/github.go#L481-L540
go
train
// getTeams retrieves a list of teams authenticated user belongs to.
func (c *githubAPIClient) getTeams() ([]teamResponse, error)
// getTeams retrieves a list of teams authenticated user belongs to. func (c *githubAPIClient) getTeams() ([]teamResponse, error)
{ var result []teamResponse bytes, nextPage, err := c.get("/user/teams") if err != nil { return nil, trace.Wrap(err) } // Extract the first page of results and append them to the full result set. var teams []teamResponse err = json.Unmarshal(bytes, &teams) if err != nil { return nil, trace.Wrap(err) } ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/github.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/github.go#L543-L568
go
train
// get makes a GET request to the provided URL using the client's token for auth
func (c *githubAPIClient) get(url string) ([]byte, string, error)
// get makes a GET request to the provided URL using the client's token for auth func (c *githubAPIClient) get(url string) ([]byte, string, error)
{ request, err := http.NewRequest("GET", fmt.Sprintf("%v%v", GithubAPIURL, url), nil) if err != nil { return nil, "", trace.Wrap(err) } request.Header.Set("Authorization", fmt.Sprintf("token %v", c.token)) response, err := http.DefaultClient.Do(request) if err != nil { return nil, "", trace.Wrap(err) } def...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/forward/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/forward/sshserver.go#L162-L189
go
train
// CheckDefaults makes sure all required parameters are passed in.
func (s *ServerConfig) CheckDefaults() error
// CheckDefaults makes sure all required parameters are passed in. func (s *ServerConfig) CheckDefaults() error
{ if s.AuthClient == nil { return trace.BadParameter("auth client required") } if s.DataDir == "" { return trace.BadParameter("missing parameter DataDir") } if s.UserAgent == nil { return trace.BadParameter("user agent required to connect to remote host") } if s.TargetConn == nil { return trace.BadParam...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/forward/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/forward/sshserver.go#L192-L262
go
train
// New creates a new unstarted Server.
func New(c ServerConfig) (*Server, error)
// New creates a new unstarted Server. func New(c ServerConfig) (*Server, error)
{ // Check and make sure we everything we need to build a forwarding node. err := c.CheckDefaults() if err != nil { return nil, trace.Wrap(err) } // Build a pipe connection to hook up the client and the server. we save both // here and will pass them along to the context when we create it so they // can be c...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/forward/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/forward/sshserver.go#L291-L300
go
train
// EmitAuditEvent sends an event to the Audit Log.
func (s *Server) EmitAuditEvent(event events.Event, fields events.EventFields)
// EmitAuditEvent sends an event to the Audit Log. func (s *Server) EmitAuditEvent(event events.Event, fields events.EventFields)
{ auditLog := s.GetAuditLog() if auditLog != nil { if err := auditLog.EmitAuditEvent(event, fields); err != nil { s.log.Error(err) } } else { s.log.Warn("SSH server has no audit log") } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/forward/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/forward/sshserver.go#L330-L342
go
train
// GetInfo returns a services.Server that represents this server.
func (s *Server) GetInfo() services.Server
// GetInfo returns a services.Server that represents this server. func (s *Server) GetInfo() services.Server
{ return &services.ServerV2{ Kind: services.KindNode, Version: services.V2, Metadata: services.Metadata{ Name: s.ID(), Namespace: s.GetNamespace(), }, Spec: services.ServerSpecV2{ Addr: s.AdvertiseAddr(), }, } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/forward/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/forward/sshserver.go#L436-L463
go
train
// Close will close all underlying connections that the forwarding server holds.
func (s *Server) Close() error
// Close will close all underlying connections that the forwarding server holds. func (s *Server) Close() error
{ conns := []io.Closer{ s.sconn, s.clientConn, s.serverConn, s.targetConn, s.remoteClient, } var errs []error for _, c := range conns { if c == nil { continue } err := c.Close() if err != nil { errs = append(errs, err) } } // Signal to waiting goroutines that the server is closing (...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/forward/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/forward/sshserver.go#L467-L497
go
train
// newRemoteSession will create and return a *ssh.Client and *ssh.Session // with a remote host.
func (s *Server) newRemoteClient(systemLogin string) (*ssh.Client, error)
// newRemoteSession will create and return a *ssh.Client and *ssh.Session // with a remote host. func (s *Server) newRemoteClient(systemLogin string) (*ssh.Client, error)
{ // the proxy will use the agent that has been forwarded to it as the auth // method when connecting to the remote host if s.userAgent == nil { return nil, trace.AccessDenied("agent must be forwarded to proxy") } authMethod := ssh.PublicKeysCallback(s.userAgent.Signers) clientConfig := &ssh.ClientConfig{ U...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/forward/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/forward/sshserver.go#L585-L644
go
train
// handleDirectTCPIPRequest handles port forwarding requests.
func (s *Server) handleDirectTCPIPRequest(ch ssh.Channel, req *sshutils.DirectTCPIPReq)
// handleDirectTCPIPRequest handles port forwarding requests. func (s *Server) handleDirectTCPIPRequest(ch ssh.Channel, req *sshutils.DirectTCPIPReq)
{ srcAddr := fmt.Sprintf("%v:%d", req.Orig, req.OrigPort) dstAddr := fmt.Sprintf("%v:%d", req.Host, req.Port) // Create context for this channel. This context will be closed when // forwarding is complete. ctx, err := srv.NewServerContext(s, s.sconn, s.identityContext) if err != nil { ctx.Errorf("Unable to cr...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/forward/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/forward/sshserver.go#L649-L724
go
train
// handleSessionRequests handles out of band session requests once the session // channel has been created this function's loop handles all the "exec", // "subsystem" and "shell" requests.
func (s *Server) handleSessionRequests(ch ssh.Channel, in <-chan *ssh.Request)
// handleSessionRequests handles out of band session requests once the session // channel has been created this function's loop handles all the "exec", // "subsystem" and "shell" requests. func (s *Server) handleSessionRequests(ch ssh.Channel, in <-chan *ssh.Request)
{ // Create context for this channel. This context will be closed when the // session request is complete. // There is no need for the forwarding server to initiate disconnects, // based on teleport business logic, because this logic is already // done on the server's terminating side. ctx, err := srv.NewServerC...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/cfg.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/cfg.go#L177-L183
go
train
// ApplyToken assigns a given token to all internal services but only if token // is not an empty string. // // Returns 'true' if token was modified
func (cfg *Config) ApplyToken(token string) bool
// ApplyToken assigns a given token to all internal services but only if token // is not an empty string. // // Returns 'true' if token was modified func (cfg *Config) ApplyToken(token string) bool
{ if token != "" { cfg.Token = token return true } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/cfg.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/cfg.go#L186-L195
go
train
// RoleConfig is a config for particular Teleport role
func (cfg *Config) RoleConfig() RoleConfig
// RoleConfig is a config for particular Teleport role func (cfg *Config) RoleConfig() RoleConfig
{ return RoleConfig{ DataDir: cfg.DataDir, HostUUID: cfg.HostUUID, HostName: cfg.Hostname, AuthServers: cfg.AuthServers, Auth: cfg.Auth, Console: cfg.Console, } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/cfg.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/cfg.go#L199-L209
go
train
// DebugDumpToYAML is useful for debugging: it dumps the Config structure into // a string
func (cfg *Config) DebugDumpToYAML() string
// DebugDumpToYAML is useful for debugging: it dumps the Config structure into // a string func (cfg *Config) DebugDumpToYAML() string
{ shallow := *cfg // do not copy sensitive data to stdout shallow.Identities = nil shallow.Auth.Authorities = nil out, err := yaml.Marshal(shallow) if err != nil { return err.Error() } return string(out) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/cfg.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/cfg.go#L227-L232
go
train
// GetRecentTTL either returns TTL that was set, // or default recent TTL value
func (c *CachePolicy) GetRecentTTL() time.Duration
// GetRecentTTL either returns TTL that was set, // or default recent TTL value func (c *CachePolicy) GetRecentTTL() time.Duration
{ if c.RecentTTL == nil { return defaults.RecentCacheTTL } return *c.RecentTTL }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/cfg.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/cfg.go#L235-L252
go
train
// String returns human-friendly representation of the policy
func (c CachePolicy) String() string
// String returns human-friendly representation of the policy func (c CachePolicy) String() string
{ if !c.Enabled { return "no cache policy" } recentCachePolicy := "" if c.GetRecentTTL() == 0 { recentCachePolicy = "will not cache frequently accessed items" } else { recentCachePolicy = fmt.Sprintf("will cache frequently accessed items for %v", c.GetRecentTTL()) } if c.NeverExpires { return fmt.Sprint...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/cfg.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/cfg.go#L412-L475
go
train
// ApplyDefaults applies default values to the existing config structure
func ApplyDefaults(cfg *Config)
// ApplyDefaults applies default values to the existing config structure func ApplyDefaults(cfg *Config)
{ // Get defaults for Cipher, Kex algorithms, and MAC algorithms from // golang.org/x/crypto/ssh default config. var sc ssh.Config sc.SetDefaults() // Remove insecure and (borderline insecure) cryptographic primitives from // default configuration. These can still be added back in file configuration by // user...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/keepalive.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/keepalive.go#L59-L102
go
train
// StartKeepAliveLoop starts the keep-alive loop.
func StartKeepAliveLoop(p KeepAliveParams)
// StartKeepAliveLoop starts the keep-alive loop. func StartKeepAliveLoop(p KeepAliveParams)
{ var missedCount int64 log := logrus.WithFields(logrus.Fields{ trace.Component: teleport.ComponentKeepAlive, }) log.Debugf("Starting keep-alive loop with with interval %v and max count %v.", p.Interval, p.MaxCount) tickerCh := time.NewTicker(p.Interval) defer tickerCh.Stop() for { select { case <-tick...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/keepalive.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/keepalive.go#L107-L127
go
train
// sendKeepAliveWithTimeout sends a keepalive@openssh.com message to the remote // client. A manual timeout is needed here because SendRequest will wait for a // response forever.
func sendKeepAliveWithTimeout(conn RequestSender, timeout time.Duration, closeContext context.Context) bool
// sendKeepAliveWithTimeout sends a keepalive@openssh.com message to the remote // client. A manual timeout is needed here because SendRequest will wait for a // response forever. func sendKeepAliveWithTimeout(conn RequestSender, timeout time.Duration, closeContext context.Context) bool
{ errorCh := make(chan error, 1) go func() { // SendRequest will unblock when connection or channel is closed. _, _, err := conn.SendRequest(teleport.KeepAliveReqType, true, nil) errorCh <- err }() select { case err := <-errorCh: if err != nil { return false } return true case <-time.After(timeo...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/namespace.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/namespace.go#L31-L41
go
train
// Check checks validity of all parameters and sets defaults
func (n *Namespace) CheckAndSetDefaults() error
// Check checks validity of all parameters and sets defaults func (n *Namespace) CheckAndSetDefaults() error
{ if err := n.Metadata.CheckAndSetDefaults(); err != nil { return trace.Wrap(err) } isValid := IsValidNamespace(n.Metadata.Name) if !isValid { return trace.BadParameter("namespace %q is invalid", n.Metadata.Name) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/namespace.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/namespace.go#L89-L91
go
train
// SetExpiry sets expiry time for the object
func (n *Namespace) SetExpiry(expires time.Time)
// SetExpiry sets expiry time for the object func (n *Namespace) SetExpiry(expires time.Time)
{ n.Metadata.SetExpiry(expires) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/namespace.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/namespace.go#L94-L96
go
train
// SetTTL sets Expires header using realtime clock
func (n *Namespace) SetTTL(clock clockwork.Clock, ttl time.Duration)
// SetTTL sets Expires header using realtime clock func (n *Namespace) SetTTL(clock clockwork.Clock, ttl time.Duration)
{ n.Metadata.SetTTL(clock, ttl) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/namespace.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/namespace.go#L128-L141
go
train
// MarshalNamespace marshals namespace to JSON
func MarshalNamespace(resource Namespace, opts ...MarshalOption) ([]byte, error)
// MarshalNamespace marshals namespace to JSON func MarshalNamespace(resource Namespace, opts ...MarshalOption) ([]byte, error)
{ cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } if !cfg.PreserveResourceID { // avoid modifying the original object // to prevent unexpected data races copy := resource copy.SetResourceID(0) resource = copy } return utils.FastMarshal(resource) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/namespace.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/namespace.go#L145-L174
go
train
// UnmarshalNamespace unmarshals role from JSON or YAML, // sets defaults and checks the schema
func UnmarshalNamespace(data []byte, opts ...MarshalOption) (*Namespace, error)
// UnmarshalNamespace unmarshals role from JSON or YAML, // sets defaults and checks the schema func UnmarshalNamespace(data []byte, opts ...MarshalOption) (*Namespace, error)
{ if len(data) == 0 { return nil, trace.BadParameter("missing namespace data") } cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } // always skip schema validation on namespaces unmarshal // the namespace is always created by teleport now var namespace Namespace if err := ut...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/namespace.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/namespace.go#L185-L187
go
train
// Less compares roles by name
func (s SortedNamespaces) Less(i, j int) bool
// Less compares roles by name func (s SortedNamespaces) Less(i, j int) bool
{ return s[i].Metadata.Name < s[j].Metadata.Name }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/namespace.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/namespace.go#L190-L192
go
train
// Swap swaps two roles in a list
func (s SortedNamespaces) Swap(i, j int)
// Swap swaps two roles in a list func (s SortedNamespaces) Swap(i, j int)
{ s[i], s[j] = s[j], s[i] }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/top_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/top_command.go#L55-L60
go
train
// Initialize allows TopCommand to plug itself into the CLI parser.
func (c *TopCommand) Initialize(app *kingpin.Application, config *service.Config)
// Initialize allows TopCommand to plug itself into the CLI parser. func (c *TopCommand) Initialize(app *kingpin.Application, config *service.Config)
{ c.config = config c.top = app.Command("top", "Report diagnostic information") c.diagURL = c.top.Arg("diag-addr", "Diagnostic HTTP URL").Default("http://127.0.0.1:3434").String() c.refreshPeriod = c.top.Arg("refresh", "Refresh period").Default("5s").Duration() }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/top_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/top_command.go#L63-L79
go
train
// TryRun takes the CLI command as an argument (like "nodes ls") and executes it.
func (c *TopCommand) TryRun(cmd string, client auth.ClientI) (match bool, err error)
// TryRun takes the CLI command as an argument (like "nodes ls") and executes it. func (c *TopCommand) TryRun(cmd string, client auth.ClientI) (match bool, err error)
{ switch cmd { case c.top.FullCommand(): diagClient, err := roundtrip.NewClient(*c.diagURL, "") if err != nil { return true, trace.Wrap(err) } err = c.Top(diagClient) if trace.IsConnectionProblem(err) { return true, trace.ConnectionProblem(err, "[CLIENT] Could not connect to metrics service at %v...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/top_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/top_command.go#L82-L133
go
train
// Top is called to execute "status" CLI command.
func (c *TopCommand) Top(client *roundtrip.Client) error
// Top is called to execute "status" CLI command. func (c *TopCommand) Top(client *roundtrip.Client) error
{ if err := ui.Init(); err != nil { return trace.Wrap(err) } defer ui.Close() ctx, cancel := context.WithCancel(context.TODO()) defer cancel() uiEvents := ui.PollEvents() ticker := time.NewTicker(*c.refreshPeriod) defer ticker.Stop() // fetch and render first time var prev *Report re, err := c.fetchAnd...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/top_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/top_command.go#L393-L405
go
train
// SortedTopRequests returns top requests sorted either // by frequency if frequency is present, or by count otherwise
func (b *BackendStats) SortedTopRequests() []Request
// SortedTopRequests returns top requests sorted either // by frequency if frequency is present, or by count otherwise func (b *BackendStats) SortedTopRequests() []Request
{ out := make([]Request, 0, len(b.TopRequests)) for _, req := range b.TopRequests { out = append(out, req) } sort.Slice(out, func(i, j int) bool { if out[i].GetFreq() == out[j].GetFreq() { return out[i].Count > out[j].Count } return out[i].GetFreq() > out[j].GetFreq() }) return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/top_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/top_command.go#L487-L493
go
train
// SetFreq sets counter frequency based on the previous value // and the time period
func (c *Counter) SetFreq(prevCount Counter, period time.Duration)
// SetFreq sets counter frequency based on the previous value // and the time period func (c *Counter) SetFreq(prevCount Counter, period time.Duration)
{ if period == 0 { return } freq := float64(c.Count-prevCount.Count) / float64(period/time.Second) c.Freq = &freq }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/top_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/top_command.go#L521-L543
go
train
// AsPercentiles interprets historgram as a bucket of percentiles // and returns calculated percentiles
func (h Histogram) AsPercentiles() []Percentile
// AsPercentiles interprets historgram as a bucket of percentiles // and returns calculated percentiles func (h Histogram) AsPercentiles() []Percentile
{ if h.Count == 0 { return nil } var percentiles []Percentile for _, bucket := range h.Buckets { if bucket.Count == 0 { continue } if bucket.Count == h.Count || math.IsInf(bucket.UpperBound, 0) { percentiles = append(percentiles, Percentile{ Percentile: 100, Value: time.Duration(bucket.U...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/top_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/top_command.go#L636-L643
go
train
// matchesLabelValue returns true if a list of label pairs // matches required name/value pair, used to slice vectors by component
func matchesLabelValue(labels []*dto.LabelPair, name, value string) bool
// matchesLabelValue returns true if a list of label pairs // matches required name/value pair, used to slice vectors by component func matchesLabelValue(labels []*dto.LabelPair, name, value string) bool
{ for _, label := range labels { if label.GetName() == name { return label.GetValue() == value } } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/fixtures/fixtures.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L13-L15
go
train
// ExpectNotFound expects not found error
func ExpectNotFound(c *check.C, err error)
// ExpectNotFound expects not found error func ExpectNotFound(c *check.C, err error)
{ c.Assert(trace.IsNotFound(err), check.Equals, true, check.Commentf("expected NotFound, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/fixtures/fixtures.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L18-L20
go
train
// ExpectBadParameter expects bad parameter error
func ExpectBadParameter(c *check.C, err error)
// ExpectBadParameter expects bad parameter error func ExpectBadParameter(c *check.C, err error)
{ c.Assert(trace.IsBadParameter(err), check.Equals, true, check.Commentf("expected BadParameter, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/fixtures/fixtures.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L23-L25
go
train
// ExpectCompareFailed expects compare failed error
func ExpectCompareFailed(c *check.C, err error)
// ExpectCompareFailed expects compare failed error func ExpectCompareFailed(c *check.C, err error)
{ c.Assert(trace.IsCompareFailed(err), check.Equals, true, check.Commentf("expected CompareFailed, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/fixtures/fixtures.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L28-L30
go
train
// ExpectAccessDenied expects error to be access denied
func ExpectAccessDenied(c *check.C, err error)
// ExpectAccessDenied expects error to be access denied func ExpectAccessDenied(c *check.C, err error)
{ c.Assert(trace.IsAccessDenied(err), check.Equals, true, check.Commentf("expected AccessDenied, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/fixtures/fixtures.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L33-L35
go
train
// ExpectAlreadyExists expects already exists error
func ExpectAlreadyExists(c *check.C, err error)
// ExpectAlreadyExists expects already exists error func ExpectAlreadyExists(c *check.C, err error)
{ c.Assert(trace.IsAlreadyExists(err), check.Equals, true, check.Commentf("expected AlreadyExists, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/fixtures/fixtures.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L38-L40
go
train
// ExpectConnectionProblem expects connection problem error
func ExpectConnectionProblem(c *check.C, err error)
// ExpectConnectionProblem expects connection problem error func ExpectConnectionProblem(c *check.C, err error)
{ c.Assert(trace.IsConnectionProblem(err), check.Equals, true, check.Commentf("expected ConnectionProblem, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/fixtures/fixtures.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L43-L47
go
train
// DeepCompare uses gocheck DeepEquals but provides nice diff if things are not equal
func DeepCompare(c *check.C, a, b interface{})
// DeepCompare uses gocheck DeepEquals but provides nice diff if things are not equal func DeepCompare(c *check.C, a, b interface{})
{ d := &spew.ConfigState{Indent: " ", DisableMethods: true, DisablePointerMethods: true, DisablePointerAddresses: true} c.Assert(a, check.DeepEquals, b, check.Commentf("%v\nStack:\n%v\n", diff.Diff(d.Sdump(a), d.Sdump(b)), string(debug.Stack()))) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/sshutils/req.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/req.go#L72-L99
go
train
// TerminalModes converts encoded terminal modes into a ssh.TerminalModes map. // The encoding is described in: https://tools.ietf.org/html/rfc4254#section-8 // // All 'encoded terminal modes' (as passed in a pty request) are encoded // into a byte stream. It is intended that the coding be portable // across dif...
func (p *PTYReqParams) TerminalModes() (ssh.TerminalModes, error)
// TerminalModes converts encoded terminal modes into a ssh.TerminalModes map. // The encoding is described in: https://tools.ietf.org/html/rfc4254#section-8 // // All 'encoded terminal modes' (as passed in a pty request) are encoded // into a byte stream. It is intended that the coding be portable // across dif...
{ terminalModes := ssh.TerminalModes{} if len(p.Modes) == 1 && p.Modes[0] == 0 { return terminalModes, nil } chunkSize := 5 for i := 0; i < len(p.Modes); i = i + chunkSize { // the first byte of the chunk is the key key := uint8(p.Modes[i]) // a key with value 0 means is the termination of the stream ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/sshutils/req.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/req.go#L102-L111
go
train
// Check validates PTY parameters.
func (p *PTYReqParams) Check() error
// Check validates PTY parameters. func (p *PTYReqParams) Check() error
{ if p.W > maxSize || p.W < minSize { return trace.BadParameter("bad width: %v", p.W) } if p.H > maxSize || p.H < minSize { return trace.BadParameter("bad height: %v", p.H) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/sshutils/req.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/req.go#L115-L124
go
train
// CheckAndSetDefaults validates PTY parameters and ensures parameters // are within default values.
func (p *PTYReqParams) CheckAndSetDefaults() error
// CheckAndSetDefaults validates PTY parameters and ensures parameters // are within default values. func (p *PTYReqParams) CheckAndSetDefaults() error
{ if p.W > maxSize || p.W < minSize { p.W = teleport.DefaultTerminalWidth } if p.H > maxSize || p.H < minSize { p.H = teleport.DefaultTerminalHeight } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/proxy/portforward.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/portforward.go#L101-L132
go
train
// httpStreamReceived is the httpstream.NewStreamHandler for port // forward streams. It checks each stream's port and stream type headers, // rejecting any streams that with missing or invalid values. Each valid // stream is sent to the streams channel.
func httpStreamReceived(ctx context.Context, streams chan httpstream.Stream) func(httpstream.Stream, <-chan struct{}) error
// httpStreamReceived is the httpstream.NewStreamHandler for port // forward streams. It checks each stream's port and stream type headers, // rejecting any streams that with missing or invalid values. Each valid // stream is sent to the streams channel. func httpStreamReceived(ctx context.Context, streams chan httpstr...
{ return func(stream httpstream.Stream, replySent <-chan struct{}) error { // make sure it has a valid port header portString := stream.Headers().Get(PortHeader) if len(portString) == 0 { return trace.BadParameter("%q header is required", PortHeader) } port, err := strconv.ParseUint(portString, 10, 16) ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/proxy/portforward.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/portforward.go#L242-L257
go
train
// getStreamPair returns a httpStreamPair for requestID. This creates a // new pair if one does not yet exist for the requestID. The returned bool is // true if the pair was created.
func (h *portForwardProxy) getStreamPair(requestID string) (*httpStreamPair, bool)
// getStreamPair returns a httpStreamPair for requestID. This creates a // new pair if one does not yet exist for the requestID. The returned bool is // true if the pair was created. func (h *portForwardProxy) getStreamPair(requestID string) (*httpStreamPair, bool)
{ h.streamPairsLock.Lock() defer h.streamPairsLock.Unlock() if p, ok := h.streamPairs[requestID]; ok { log.Infof("(conn=%p, request=%s) found existing stream pair", h.sourceConn, requestID) return p, false } log.Infof("(conn=%p, request=%s) creating new stream pair", h.sourceConn, requestID) p := newPortF...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/proxy/portforward.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/portforward.go#L262-L271
go
train
// monitorStreamPair waits for the pair to receive both its error and data // streams, or for the timeout to expire (whichever happens first), and then // removes the pair.
func (h *portForwardProxy) monitorStreamPair(p *httpStreamPair, timeout <-chan time.Time)
// monitorStreamPair waits for the pair to receive both its error and data // streams, or for the timeout to expire (whichever happens first), and then // removes the pair. func (h *portForwardProxy) monitorStreamPair(p *httpStreamPair, timeout <-chan time.Time)
{ select { case <-timeout: err := fmt.Errorf("(conn=%v, request=%s) timed out waiting for streams", h.sourceConn, p.requestID) p.printError(err.Error()) case <-p.complete: log.Infof("(conn=%v, request=%s) successfully received error and data streams", h.sourceConn, p.requestID) } h.removeStreamPair(p.reques...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/proxy/portforward.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/portforward.go#L284-L289
go
train
// removeStreamPair removes the stream pair identified by requestID from streamPairs.
func (h *portForwardProxy) removeStreamPair(requestID string)
// removeStreamPair removes the stream pair identified by requestID from streamPairs. func (h *portForwardProxy) removeStreamPair(requestID string)
{ h.streamPairsLock.Lock() defer h.streamPairsLock.Unlock() delete(h.streamPairs, requestID) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/proxy/portforward.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/portforward.go#L292-L298
go
train
// requestID returns the request id for stream.
func (h *portForwardProxy) requestID(stream httpstream.Stream) (string, error)
// requestID returns the request id for stream. func (h *portForwardProxy) requestID(stream httpstream.Stream) (string, error)
{ requestID := stream.Headers().Get(PortForwardRequestIDHeader) if len(requestID) == 0 { return "", trace.BadParameter("port forwarding is not supported") } return requestID, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/proxy/portforward.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/portforward.go#L303-L334
go
train
// run is the main loop for the portForwardProxy. It processes new // streams, invoking portForward for each complete stream pair. The loop exits // when the httpstream.Connection is closed.
func (h *portForwardProxy) run()
// run is the main loop for the portForwardProxy. It processes new // streams, invoking portForward for each complete stream pair. The loop exits // when the httpstream.Connection is closed. func (h *portForwardProxy) run()
{ h.Debugf("Waiting for port forward streams.") for { select { case <-h.context.Done(): h.Debugf("Context is closing, returning.") return case <-h.sourceConn.CloseChan(): h.Debugf("Upgraded connection closed.") return case stream := <-h.streamChan: requestID, err := h.requestID(stream) if e...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/proxy/portforward.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/portforward.go#L338-L353
go
train
// portForward invokes the portForwardProxy's forwarder.PortForward // function for the given stream pair.
func (h *portForwardProxy) portForward(p *httpStreamPair)
// portForward invokes the portForwardProxy's forwarder.PortForward // function for the given stream pair. func (h *portForwardProxy) portForward(p *httpStreamPair)
{ defer p.dataStream.Close() defer p.errorStream.Close() portString := p.dataStream.Headers().Get(PortHeader) port, _ := strconv.ParseInt(portString, 10, 32) h.Debugf("Forwrarding port %v -> %v.", p.requestID, portString) err := h.forwardStreamPair(p, port) h.Debugf("Completed forwrarding port %v -> %v.", p.r...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/proxy/portforward.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/portforward.go#L377-L399
go
train
// add adds the stream to the httpStreamPair. If the pair already // contains a stream for the new stream's type, an error is returned. add // returns true if both the data and error streams for this pair have been // received.
func (p *httpStreamPair) add(stream httpstream.Stream) (bool, error)
// add adds the stream to the httpStreamPair. If the pair already // contains a stream for the new stream's type, an error is returned. add // returns true if both the data and error streams for this pair have been // received. func (p *httpStreamPair) add(stream httpstream.Stream) (bool, error)
{ p.lock.Lock() defer p.lock.Unlock() switch stream.Headers().Get(StreamType) { case StreamTypeError: if p.errorStream != nil { return false, trace.BadParameter("error stream already assigned") } p.errorStream = stream case StreamTypeData: if p.dataStream != nil { return false, trace.BadParameter("...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/replace.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/replace.go#L30-L47
go
train
// 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 ...
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 ...
{ if !strings.HasPrefix(expression, "^") || !strings.HasSuffix(expression, "$") { // replace glob-style wildcards with regexp wildcards // for plain strings, and quote all characters that could // be interpreted in regular expression expression = "^" + GlobToRegexp(expression) + "$" } expr, err := regexp.Co...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/replace.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/replace.go#L51-L74
go
train
// SliceMatchesRegex checks if input matches any of the expressions. The // match is always evaluated as a regex either an exact match or regexp.
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 SliceMatchesRegex(input string, expressions []string) (bool, error)
{ for _, expression := range expressions { if !strings.HasPrefix(expression, "^") || !strings.HasSuffix(expression, "$") { // replace glob-style wildcards with regexp wildcards // for plain strings, and quote all characters that could // be interpreted in regular expression expression = "^" + GlobToRege...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/state.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L44-L61
go
train
// NewProcessStorage returns a new instance of the process storage.
func NewProcessStorage(ctx context.Context, path string) (*ProcessStorage, error)
// NewProcessStorage returns a new instance of the process storage. func NewProcessStorage(ctx context.Context, path string) (*ProcessStorage, error)
{ if path == "" { return nil, trace.BadParameter("missing parameter path") } litebk, err := lite.NewWithConfig(ctx, lite.Config{Path: path, EventsOff: true}) if err != nil { return nil, trace.Wrap(err) } // Import storage data err = legacy.Import(ctx, litebk, func() (legacy.Exporter, error) { return dir.N...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/state.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L84-L94
go
train
// GetState reads rotation state from disk.
func (p *ProcessStorage) GetState(role teleport.Role) (*StateV2, error)
// GetState reads rotation state from disk. func (p *ProcessStorage) GetState(role teleport.Role) (*StateV2, error)
{ item, err := p.Get(context.TODO(), backend.Key(statesPrefix, strings.ToLower(role.String()), stateName)) if err != nil { return nil, trace.Wrap(err) } var res StateV2 if err := utils.UnmarshalWithSchema(GetStateSchema(), &res, item.Value); err != nil { return nil, trace.BadParameter(err.Error()) } return ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/state.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L97-L114
go
train
// CreateState creates process state if it does not exist yet.
func (p *ProcessStorage) CreateState(role teleport.Role, state StateV2) error
// CreateState creates process state if it does not exist yet. func (p *ProcessStorage) CreateState(role teleport.Role, state StateV2) error
{ if err := state.CheckAndSetDefaults(); err != nil { return trace.Wrap(err) } value, err := json.Marshal(state) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(statesPrefix, strings.ToLower(role.String()), stateName), Value: value, } _, err = p.Create(context.TODO(), ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/state.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L137-L156
go
train
// ReadIdentity reads identity using identity name and role.
func (p *ProcessStorage) ReadIdentity(name string, role teleport.Role) (*Identity, error)
// ReadIdentity reads identity using identity name and role. func (p *ProcessStorage) ReadIdentity(name string, role teleport.Role) (*Identity, error)
{ if name == "" { return nil, trace.BadParameter("missing parameter name") } item, err := p.Get(context.TODO(), backend.Key(idsPrefix, strings.ToLower(role.String()), name)) if err != nil { return nil, trace.Wrap(err) } var res IdentityV2 if err := utils.UnmarshalWithSchema(GetIdentitySchema(), &res, item.V...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/state.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L159-L189
go
train
// WriteIdentity writes identity to the backend.
func (p *ProcessStorage) WriteIdentity(name string, id Identity) error
// WriteIdentity writes identity to the backend. func (p *ProcessStorage) WriteIdentity(name string, id Identity) error
{ res := IdentityV2{ ResourceHeader: services.ResourceHeader{ Kind: services.KindIdentity, Version: services.V2, Metadata: services.Metadata{ Name: name, }, }, Spec: IdentitySpecV2{ Key: id.KeyBytes, SSHCert: id.CertBytes, TLSCert: id.TLSCertBytes, TLSCACerts: id.TLSC...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/state.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L200-L211
go
train
// CheckAndSetDefaults checks and sets defaults values.
func (s *StateV2) CheckAndSetDefaults() error
// CheckAndSetDefaults checks and sets defaults values. func (s *StateV2) CheckAndSetDefaults() error
{ s.Kind = services.KindState s.Version = services.V2 // for state resource name does not matter if s.Metadata.Name == "" { s.Metadata.Name = stateName } if err := s.Metadata.CheckAndSetDefaults(); err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/state.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L228-L250
go
train
// CheckAndSetDefaults checks and sets defaults values.
func (s *IdentityV2) CheckAndSetDefaults() error
// CheckAndSetDefaults checks and sets defaults values. func (s *IdentityV2) CheckAndSetDefaults() error
{ s.Kind = services.KindIdentity s.Version = services.V2 if err := s.Metadata.CheckAndSetDefaults(); err != nil { return trace.Wrap(err) } if len(s.Spec.Key) == 0 { return trace.BadParameter("missing parameter Key") } if len(s.Spec.SSHCert) == 0 { return trace.BadParameter("missing parameter SSHCert") } ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/state.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L289-L291
go
train
// GetIdentitySchema returns JSON Schema for cert authorities.
func GetIdentitySchema() string
// GetIdentitySchema returns JSON Schema for cert authorities. func GetIdentitySchema() string
{ return fmt.Sprintf(services.V2SchemaTemplate, services.MetadataSchema, IdentitySpecV2Schema, services.DefaultDefinitions) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/state.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L304-L306
go
train
// GetStateSchema returns JSON Schema for cert authorities.
func GetStateSchema() string
// GetStateSchema returns JSON Schema for cert authorities. func GetStateSchema() string
{ return fmt.Sprintf(services.V2SchemaTemplate, services.MetadataSchema, fmt.Sprintf(StateSpecV2Schema, services.RotationSchema), services.DefaultDefinitions) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/api.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/api.go#L251-L257
go
train
// String returns a string representation of an event structure
func (f EventFields) AsString() string
// String returns a string representation of an event structure func (f EventFields) AsString() string
{ return fmt.Sprintf("%s: login=%s, id=%v, bytes=%v", f.GetString(EventType), f.GetString(EventLogin), f.GetInt(EventCursor), f.GetInt(SessionPrintEventBytes)) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/api.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/api.go#L280-L287
go
train
// GetString returns a string representation of a logged field
func (f EventFields) GetString(key string) string
// GetString returns a string representation of a logged field func (f EventFields) GetString(key string) string
{ val, found := f[key] if !found { return "" } v, _ := val.(string) return v }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/api.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/api.go#L290-L303
go
train
// GetString returns an int representation of a logged field
func (f EventFields) GetInt(key string) int
// GetString returns an int representation of a logged field func (f EventFields) GetInt(key string) int
{ val, found := f[key] if !found { return 0 } v, ok := val.(int) if !ok { f, ok := val.(float64) if ok { v = int(f) } } return v }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/api.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/api.go#L306-L317
go
train
// GetString returns an int representation of a logged field
func (f EventFields) GetTime(key string) time.Time
// GetString returns an int representation of a logged field func (f EventFields) GetTime(key string) time.Time
{ val, found := f[key] if !found { return time.Time{} } v, ok := val.(time.Time) if !ok { s := f.GetString(key) v, _ = time.Parse(time.RFC3339, s) } return v }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/proxy/remotecommand.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/remotecommand.go#L311-L317
go
train
// waitStreamReply waits until either replySent or stop is closed. If replySent is closed, it sends // an empty struct to the notify channel.
func waitStreamReply(ctx context.Context, replySent <-chan struct{}, notify chan<- struct{})
// waitStreamReply waits until either replySent or stop is closed. If replySent is closed, it sends // an empty struct to the notify channel. func waitStreamReply(ctx context.Context, replySent <-chan struct{}, notify chan<- struct{})
{ select { case <-replySent: notify <- struct{}{} case <-ctx.Done(): } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/fs.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L36-L56
go
train
// 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...
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...
{ if customPath == "" { homeDir := getHomeDir() if homeDir == "" { return "", trace.BadParameter("no path provided and environment variable %v is not not set", teleport.EnvHome) } customPath = filepath.Join(homeDir, defaultLocalDir, defaultLocalPath) } baseDir := filepath.Dir(customPath) _, err := StatD...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/fs.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L59-L65
go
train
// MkdirAll creates directory and subdirectories
func MkdirAll(targetDirectory string, mode os.FileMode) error
// MkdirAll creates directory and subdirectories func MkdirAll(targetDirectory string, mode os.FileMode) error
{ err := os.MkdirAll(targetDirectory, mode) if err != nil { return trace.ConvertSystemError(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/fs.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L74-L76
go
train
// Close removes directory and all it's contents
func (r *RemoveDirCloser) Close() error
// Close removes directory and all it's contents func (r *RemoveDirCloser) Close() error
{ return trace.ConvertSystemError(os.RemoveAll(r.Path)) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/fs.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L79-L85
go
train
// IsFile returns true if a given file path points to an existing file
func IsFile(fp string) bool
// IsFile returns true if a given file path points to an existing file func IsFile(fp string) bool
{ fi, err := os.Stat(fp) if err == nil { return !fi.IsDir() } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/fs.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L88-L94
go
train
// IsDir is a helper function to quickly check if a given path is a valid directory
func IsDir(dirPath string) bool
// IsDir is a helper function to quickly check if a given path is a valid directory func IsDir(dirPath string) bool
{ fi, err := os.Stat(dirPath) if err == nil { return fi.IsDir() } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/fs.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L100-L113
go
train
// 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 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 ReadAll(r io.Reader, bufsize int) (out []byte, err error)
{ buff := make([]byte, bufsize) n := 0 for err == nil { n, err = r.Read(buff) if n > 0 { out = append(out, buff[:n]...) } } if err == io.EOF { err = nil } return out, err }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/fs.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L117-L127
go
train
// NormalizePath normalises path, evaluating symlinks and converting local // paths to absolute
func NormalizePath(path string) (string, error)
// NormalizePath normalises path, evaluating symlinks and converting local // paths to absolute func NormalizePath(path string) (string, error)
{ s, err := filepath.Abs(path) if err != nil { return "", trace.ConvertSystemError(err) } abs, err := filepath.EvalSymlinks(s) if err != nil { return "", trace.ConvertSystemError(err) } return abs, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/fs.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L130-L147
go
train
// OpenFile opens file and returns file handle
func OpenFile(path string) (*os.File, error)
// OpenFile opens file and returns file handle func OpenFile(path string) (*os.File, error)
{ newPath, err := NormalizePath(path) if err != nil { return nil, trace.Wrap(err) } fi, err := os.Stat(newPath) if err != nil { return nil, trace.ConvertSystemError(err) } if fi.IsDir() { return nil, trace.BadParameter("%v is not a file", path) } f, err := os.Open(newPath) if err != nil { return nil,...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/fs.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L150-L159
go
train
// StatDir stats directory, returns error if file exists, but not a directory
func StatDir(path string) (os.FileInfo, error)
// StatDir stats directory, returns error if file exists, but not a directory func StatDir(path string) (os.FileInfo, error)
{ fi, err := os.Stat(path) if err != nil { return nil, trace.ConvertSystemError(err) } if !fi.IsDir() { return nil, trace.BadParameter("%v is not a directory", path) } return fi, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/fs.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L162-L172
go
train
// getHomeDir returns the home directory based off the OS.
func getHomeDir() string
// getHomeDir returns the home directory based off the OS. func getHomeDir() string
{ switch runtime.GOOS { case teleport.LinuxOS: return os.Getenv(teleport.EnvHome) case teleport.DarwinOS: return os.Getenv(teleport.EnvHome) case teleport.WindowsOS: return os.Getenv(teleport.EnvUserProfile) } return "" }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/listener.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/listener.go#L11-L19
go
train
// GetListenerFile returns file associated with listener
func GetListenerFile(listener net.Listener) (*os.File, error)
// GetListenerFile returns file associated with listener func GetListenerFile(listener net.Listener) (*os.File, error)
{ switch t := listener.(type) { case *net.TCPListener: return t.File() case *net.UnixListener: return t.File() } return nil, trace.BadParameter("unsupported listener: %T", listener) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/buf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/buf.go#L25-L36
go
train
// NewSyncBuffer returns new in memory buffer
func NewSyncBuffer() *SyncBuffer
// NewSyncBuffer returns new in memory buffer func NewSyncBuffer() *SyncBuffer
{ reader, writer := io.Pipe() buf := &bytes.Buffer{} go func() { io.Copy(buf, reader) }() return &SyncBuffer{ reader: reader, writer: writer, buf: buf, } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/buf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/buf.go#L65-L72
go
train
// Close closes reads and writes on the buffer
func (b *SyncBuffer) Close() error
// Close closes reads and writes on the buffer func (b *SyncBuffer) Close() error
{ err := b.reader.Close() err2 := b.writer.Close() if err != nil { return err } return err2 }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/agent.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/agent.go#L97-L120
go
train
// CheckAndSetDefaults checks parameters and sets default values
func (a *AgentConfig) CheckAndSetDefaults() error
// CheckAndSetDefaults checks parameters and sets default values func (a *AgentConfig) CheckAndSetDefaults() error
{ if a.Addr.IsEmpty() { return trace.BadParameter("missing parameter Addr") } if a.Context == nil { return trace.BadParameter("missing parameter Context") } if a.Client == nil { return trace.BadParameter("missing parameter Client") } if a.AccessPoint == nil { return trace.BadParameter("missing parameter...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/agent.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/agent.go#L150-L174
go
train
// NewAgent returns a new reverse tunnel agent
func NewAgent(cfg AgentConfig) (*Agent, error)
// NewAgent returns a new reverse tunnel agent func NewAgent(cfg AgentConfig) (*Agent, error)
{ if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } ctx, cancel := context.WithCancel(cfg.Context) a := &Agent{ AgentConfig: cfg, ctx: ctx, cancel: cancel, authMethods: []ssh.AuthMethod{ssh.PublicKeys(cfg.Signers...)}, } if len(cfg.DiscoverProxies) == 0 { a....
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/agent.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/agent.go#L230-L237
go
train
// connectedTo returns true if connected services.Server passed in.
func (a *Agent) connectedTo(proxy services.Server) bool
// connectedTo returns true if connected services.Server passed in. func (a *Agent) connectedTo(proxy services.Server) bool
{ principals := a.getPrincipals() proxyID := fmt.Sprintf("%v.%v", proxy.GetName(), a.ClusterName) if _, ok := principals[proxyID]; ok { return true } return false }