You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.4 KiB

  1. package privval
  2. import (
  3. "net"
  4. "time"
  5. )
  6. // timeoutError can be used to check if an error returned from the netp package
  7. // was due to a timeout.
  8. type timeoutError interface {
  9. Timeout() bool
  10. }
  11. // tcpTimeoutListener implements net.Listener.
  12. var _ net.Listener = (*tcpTimeoutListener)(nil)
  13. // tcpTimeoutListener wraps a *net.TCPListener to standardise protocol timeouts
  14. // and potentially other tuning parameters.
  15. type tcpTimeoutListener struct {
  16. *net.TCPListener
  17. acceptDeadline time.Duration
  18. connDeadline time.Duration
  19. period time.Duration
  20. }
  21. // newTCPTimeoutListener returns an instance of tcpTimeoutListener.
  22. func newTCPTimeoutListener(
  23. ln net.Listener,
  24. acceptDeadline, connDeadline time.Duration,
  25. period time.Duration,
  26. ) tcpTimeoutListener {
  27. return tcpTimeoutListener{
  28. TCPListener: ln.(*net.TCPListener),
  29. acceptDeadline: acceptDeadline,
  30. connDeadline: connDeadline,
  31. period: period,
  32. }
  33. }
  34. // Accept implements net.Listener.
  35. func (ln tcpTimeoutListener) Accept() (net.Conn, error) {
  36. err := ln.SetDeadline(time.Now().Add(ln.acceptDeadline))
  37. if err != nil {
  38. return nil, err
  39. }
  40. tc, err := ln.AcceptTCP()
  41. if err != nil {
  42. return nil, err
  43. }
  44. if err := tc.SetDeadline(time.Now().Add(ln.connDeadline)); err != nil {
  45. return nil, err
  46. }
  47. if err := tc.SetKeepAlive(true); err != nil {
  48. return nil, err
  49. }
  50. if err := tc.SetKeepAlivePeriod(ln.period); err != nil {
  51. return nil, err
  52. }
  53. return tc, nil
  54. }