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.

90 lines
2.0 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. // timeoutConn wraps a net.Conn to standardise protocol timeouts / deadline resets.
  22. type timeoutConn struct {
  23. net.Conn
  24. connDeadline time.Duration
  25. }
  26. // newTCPTimeoutListener returns an instance of tcpTimeoutListener.
  27. func newTCPTimeoutListener(
  28. ln net.Listener,
  29. acceptDeadline, connDeadline time.Duration,
  30. period time.Duration,
  31. ) tcpTimeoutListener {
  32. return tcpTimeoutListener{
  33. TCPListener: ln.(*net.TCPListener),
  34. acceptDeadline: acceptDeadline,
  35. connDeadline: connDeadline,
  36. period: period,
  37. }
  38. }
  39. // newTimeoutConn returns an instance of newTCPTimeoutConn.
  40. func newTimeoutConn(
  41. conn net.Conn,
  42. connDeadline time.Duration) *timeoutConn {
  43. return &timeoutConn{
  44. conn,
  45. connDeadline,
  46. }
  47. }
  48. // Accept implements net.Listener.
  49. func (ln tcpTimeoutListener) Accept() (net.Conn, error) {
  50. err := ln.SetDeadline(time.Now().Add(ln.acceptDeadline))
  51. if err != nil {
  52. return nil, err
  53. }
  54. tc, err := ln.AcceptTCP()
  55. if err != nil {
  56. return nil, err
  57. }
  58. // Wrap the conn in our timeout wrapper
  59. conn := newTimeoutConn(tc, ln.connDeadline)
  60. return conn, nil
  61. }
  62. // Read implements net.Listener.
  63. func (c timeoutConn) Read(b []byte) (n int, err error) {
  64. // Reset deadline
  65. c.Conn.SetReadDeadline(time.Now().Add(c.connDeadline))
  66. return c.Conn.Read(b)
  67. }
  68. // Write implements net.Listener.
  69. func (c timeoutConn) Write(b []byte) (n int, err error) {
  70. // Reset deadline
  71. c.Conn.SetWriteDeadline(time.Now().Add(c.connDeadline))
  72. return c.Conn.Write(b)
  73. }