context.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright (c) 2022 Tailscale Inc & AUTHORS All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package tailssh
  5. import (
  6. "sync"
  7. "time"
  8. )
  9. // sshContext is the context.Context implementation we use for SSH
  10. // that adds a CloseWithError method. Otherwise it's just a normalish
  11. // Context.
  12. type sshContext struct {
  13. mu sync.Mutex
  14. closed bool
  15. done chan struct{}
  16. err error
  17. }
  18. func newSSHContext() *sshContext {
  19. return &sshContext{done: make(chan struct{})}
  20. }
  21. func (ctx *sshContext) CloseWithError(err error) {
  22. ctx.mu.Lock()
  23. defer ctx.mu.Unlock()
  24. if ctx.closed {
  25. return
  26. }
  27. ctx.closed = true
  28. ctx.err = err
  29. close(ctx.done)
  30. }
  31. func (ctx *sshContext) Err() error {
  32. ctx.mu.Lock()
  33. defer ctx.mu.Unlock()
  34. return ctx.err
  35. }
  36. func (ctx *sshContext) Done() <-chan struct{} { return ctx.done }
  37. func (ctx *sshContext) Deadline() (deadline time.Time, ok bool) { return }
  38. func (ctx *sshContext) Value(any) any { return nil }
  39. // userVisibleError is a wrapper around an error that implements
  40. // SSHTerminationError, so msg is written to their session.
  41. type userVisibleError struct {
  42. msg string
  43. error
  44. }
  45. func (ue userVisibleError) SSHTerminationMessage() string { return ue.msg }
  46. // SSHTerminationError is implemented by errors that terminate an SSH
  47. // session and should be written to user's sessions.
  48. type SSHTerminationError interface {
  49. error
  50. SSHTerminationMessage() string
  51. }