在Go中设置idletimeout

huangapple go评论97阅读模式
英文:

Setting idletimeout in Go

问题

我在Go语言中有一个处理通过TCP传入并通过SSH处理的连接的函数。我正在尝试通过在连接函数中创建结构体来设置空闲超时时间。

用例 - 客户应该能够建立连接并上传/下载多个文件

参考 - https://stackoverflow.com/questions/47912263/idletimeout-in-tcp-server

函数代码:

  1. type Conn struct {
  2. net.Conn
  3. idleTimeout time.Duration
  4. }
  5. func HandleConn(conn net.Conn) {
  6. var err error
  7. rAddr := conn.RemoteAddr()
  8. session := shortuuid.New()
  9. config := LoadSSHServerConfig(session)
  10. blocklistItem := blocklist.GetBlockListItem(rAddr)
  11. if blocklistItem.IsBlocked() {
  12. conn.Close()
  13. atomic.AddInt64(&stats.Stats.BlockedConnections, 1)
  14. return
  15. }
  16. func (c *Conn) Read(b []byte) (int, error) {
  17. err := c.Conn.SetReadDeadline(time.Now().Add(c.idleTimeout))
  18. if err != nil {
  19. return 0, err
  20. }
  21. return c.Conn.Read(b)
  22. }
  23. sConn, chans, reqs, err := ssh.NewServerConn(conn, config)
  24. if err != nil {
  25. if err == io.EOF {
  26. log.Errorw("SSH: Handshaking was terminated", log.Fields{
  27. "address": rAddr,
  28. "error": err,
  29. "session": session})
  30. } else {
  31. log.Errorw("SSH: Error on handshaking", log.Fields{
  32. "address": rAddr,
  33. "error": err,
  34. "session": session})
  35. }
  36. atomic.AddInt64(&stats.Stats.AuthorizationFailed, 1)
  37. return
  38. }
  39. log.Infow("connection accepted", log.Fields{
  40. "user": sConn.User(),
  41. })
  42. if user, ok := users[session]; ok {
  43. log.Infow("SSH: Connection accepted", log.Fields{
  44. "user": user.LogFields(),
  45. "clientVersion": string(sConn.ClientVersion())})
  46. atomic.AddInt64(&stats.Stats.AuthorizationSucceeded, 1)
  47. // The incoming Request channel must be serviced.
  48. go ssh.DiscardRequests(reqs)
  49. // Key ID: sConn.Permissions.Extensions["key-id"]
  50. handleServerConn(user, chans)
  51. log.Infow("connection finished", log.Fields{"user": user.LogFields()})
  52. log.Infow("checking connections", log.Fields{
  53. // "cc": Stats.AcceptedConnections,
  54. "cc2": &stats.Stats.AcceptedConnections})
  55. // Remove connection from local cache
  56. delete(users, session)
  57. } else {
  58. log.Infow("user not found from memory", log.Fields{"username": sConn.User()})
  59. }
  60. }

这段代码来自Listen函数:

  1. func Listen() {
  2. listener, err := net.Listen("tcp", sshListen)
  3. if err != nil {
  4. panic(err)
  5. }
  6. if useProxyProtocol {
  7. listener = &proxyproto.Listener{
  8. Listener: listener,
  9. ProxyHeaderTimeout: time.Second * 10,
  10. }
  11. }
  12. for {
  13. // Once a ServerConfig has been configured, connections can be accepted.
  14. conn, err := listener.Accept()
  15. if err != nil {
  16. log.Errorw("SSH: Error accepting incoming connection", log.Fields{"error": err})
  17. atomic.AddInt64(&stats.Stats.FailedConnections, 1)
  18. continue
  19. }
  20. // Before use, a handshake must be performed on the incoming net.Conn.
  21. // It must be handled in a separate goroutine,
  22. // otherwise one user could easily block entire loop.
  23. // For example, user could be asked to trust server key fingerprint and hangs.
  24. go HandleConn(conn)
  25. }
  26. }

是否可能仅为空闲超过20秒(无上传/下载)的连接设置截止时间?

编辑1:根据@LiamKelly的建议,我已经对代码进行了更改。现在代码如下:

  1. type SshProxyConn struct {
  2. net.Conn
  3. idleTimeout time.Duration
  4. }
  5. func (c *SshProxyConn) Read(b []byte) (int, error) {
  6. err := c.Conn.SetReadDeadline(time.Now().Add(c.idleTimeout))
  7. if err != nil {
  8. return 0, err
  9. }
  10. return c.Conn.Read(b)
  11. }
  12. func HandleConn(conn net.Conn) {
  13. //与上述代码相同的行
  14. sshproxyconn := &SshProxyConn{nil, time.Second * 20}
  15. Conn, chans, reqs, err := ssh.NewServerConn(sshproxyconn, config)
  16. //与上述代码相同的行
  17. }
  18. 但现在的问题是SSH无法进行当我尝试进行SSH我收到错误消息"Connection closed"它是否仍在等待函数调用中的"conn"变量
  19. <details>
  20. <summary>英文:</summary>
  21. I have a function in go which is handling connections which are coming through tcp and handled via ssh. I am trying to set an idle timeout by creating struct in the connection function.
  22. **Use case** - a customer should be able to make a connection and upload/download multiple files
  23. **Reference** - https://stackoverflow.com/questions/47912263/idletimeout-in-tcp-server
  24. Function code:
  25. type Conn struct {
  26. net.Conn
  27. idleTimeout time.Duration
  28. }
  29. func HandleConn(conn net.Conn) {
  30. var err error
  31. rAddr := conn.RemoteAddr()
  32. session := shortuuid.New()
  33. config := LoadSSHServerConfig(session)
  34. blocklistItem := blocklist.GetBlockListItem(rAddr)
  35. if blocklistItem.IsBlocked() {
  36. conn.Close()
  37. atomic.AddInt64(&amp;stats.Stats.BlockedConnections, 1)
  38. return
  39. }
  40. func (c *Conn) Read(b []byte) (int, error) {
  41. err := c.Conn.SetReadDeadline(time.Now().Add(c.idleTimeout))
  42. if err != nil {
  43. return 0, err
  44. }
  45. return c.Conn.Read(b)
  46. }
  47. sConn, chans, reqs, err := ssh.NewServerConn(conn, config)
  48. if err != nil {
  49. if err == io.EOF {
  50. log.Errorw(&quot;SSH: Handshaking was terminated&quot;, log.Fields{
  51. &quot;address&quot;: rAddr,
  52. &quot;error&quot;: err,
  53. &quot;session&quot;: session})
  54. } else {
  55. log.Errorw(&quot;SSH: Error on handshaking&quot;, log.Fields{
  56. &quot;address&quot;: rAddr,
  57. &quot;error&quot;: err,
  58. &quot;session&quot;: session})
  59. }
  60. atomic.AddInt64(&amp;stats.Stats.AuthorizationFailed, 1)
  61. return
  62. }
  63. log.Infow(&quot;connection accepted&quot;, log.Fields{
  64. &quot;user&quot;: sConn.User(),
  65. })
  66. if user, ok := users[session]; ok {
  67. log.Infow(&quot;SSH: Connection accepted&quot;, log.Fields{
  68. &quot;user&quot;: user.LogFields(),
  69. &quot;clientVersion&quot;: string(sConn.ClientVersion())})
  70. atomic.AddInt64(&amp;stats.Stats.AuthorizationSucceeded, 1)
  71. // The incoming Request channel must be serviced.
  72. go ssh.DiscardRequests(reqs)
  73. // Key ID: sConn.Permissions.Extensions[&quot;key-id&quot;]
  74. handleServerConn(user, chans)
  75. log.Infow(&quot;connection finished&quot;, log.Fields{&quot;user&quot;: user.LogFields()})
  76. log.Infow(&quot;checking connections&quot;, log.Fields{
  77. //&quot;cc&quot;: Stats.AcceptedConnections,
  78. &quot;cc2&quot;: &amp;stats.Stats.AcceptedConnections})
  79. // Remove connection from local cache
  80. delete(users, session)
  81. } else {
  82. log.Infow(&quot;user not found from memory&quot;, log.Fields{&quot;username&quot;: sConn.User()})
  83. }
  84. }
  85. This code is coming from the Listen function:
  86. func Listen() {
  87. listener, err := net.Listen(&quot;tcp&quot;, sshListen)
  88. if err != nil {
  89. panic(err)
  90. }
  91. if useProxyProtocol {
  92. listener = &amp;proxyproto.Listener{
  93. Listener: listener,
  94. ProxyHeaderTimeout: time.Second * 10,
  95. }
  96. }
  97. for {
  98. // Once a ServerConfig has been configured, connections can be accepted.
  99. conn, err := listener.Accept()
  100. if err != nil {
  101. log.Errorw(&quot;SSH: Error accepting incoming connection&quot;, log.Fields{&quot;error&quot;: err})
  102. atomic.AddInt64(&amp;stats.Stats.FailedConnections, 1)
  103. continue
  104. }
  105. // Before use, a handshake must be performed on the incoming net.Conn.
  106. // It must be handled in a separate goroutine,
  107. // otherwise one user could easily block entire loop.
  108. // For example, user could be asked to trust server key fingerprint and hangs.
  109. go HandleConn(conn)
  110. }
  111. }
  112. Is that even possible to set a deadline for only the connections which have been idle for 20 secinds (no upload/downloads).
  113. **EDIT 1** : Following @LiamKelly&#39;s suggestions, I have made the changes in the code. Now the code is like
  114. type SshProxyConn struct {
  115. net.Conn
  116. idleTimeout time.Duration
  117. }
  118. func (c *SshProxyConn) Read(b []byte) (int, error) {
  119. err := c.Conn.SetReadDeadline(time.Now().Add(c.idleTimeout))
  120. if err != nil {
  121. return 0, err
  122. }
  123. return c.Conn.Read(b)
  124. }
  125. func HandleConn(conn net.Conn) {
  126. //lines of code as above
  127. sshproxyconn := &amp;SshProxyConn{nil, time.Second * 20}
  128. Conn, chans, reqs, err := ssh.NewServerConn(sshproxyconn, config)
  129. //lines of code
  130. }
  131. But now the issue is that SSH is not happening. I am getting the error &quot;Connection closed&quot; when I try to do ssh. Is it still waiting for &quot;conn&quot; variable in the function call?
  132. </details>
  133. # 答案1
  134. **得分**: 1
  135. &gt; 是否可能仅为空闲超过20秒的连接设置截止日期
  136. 首先我要声明一下我会假设`go-protoproxy`实现了我们期望的`Conn`接口另外正如你之前暗示的我认为你不能将一个结构体方法放在另一个函数内我还建议将其重命名为一个独特的名称以避免`Conn``net.Conn`混淆)。
  137. ```go
  138. type SshProxyConn struct {
  139. net.Conn
  140. idleTimeout time.Duration
  141. }
  142. func (c *SshProxyConn) Read(b []byte) (int, error) {
  143. err := c.Conn.SetReadDeadline(time.Now().Add(c.idleTimeout))
  144. if err != nil {
  145. return 0, err
  146. }
  147. return c.Conn.Read(b)
  148. }
  149. func HandleConn(conn net.Conn) {

这样更清楚地显示了你的主要问题,你将普通的net.Conn传递给了SSH服务器,而不是你的包装类。所以

  1. sConn, chans, reqs, err := ssh.NewServerConn(conn, config)

应该更改为 编辑

  1. sshproxyconn := &SshProxyConn{conn, time.Second * 20}
  2. Conn, chans, reqs, err := ssh.NewServerConn(sshproxyconn, config)
英文:

> Is that even possible to set a deadline for only the connections which have been idle for 20 [seconds]

Ok so first a general disclaimer, I am going to assume go-protoproxy implements the Conn interface as we would expected. Also as you hinted at before, I don't think you can put a a struct method inside another function (I also recommend renaming it something unique to prevent Conn vs net.Conn confusion).

  1. type SshProxyConn struct {
  2. net.Conn
  3. idleTimeout time.Duration
  4. }
  5. func (c *SshProxyConn) Read(b []byte) (int, error) {
  6. err := c.Conn.SetReadDeadline(time.Now().Add(c.idleTimeout))
  7. if err != nil {
  8. return 0, err
  9. }
  10. return c.Conn.Read(b)
  11. }
  12. func HandleConn(conn net.Conn) {

This makes is more clear what your primary issue is, which you passed the normal net.Conn to your SSH server, not your wrapper class. So

  1. sConn, chans, reqs, err := ssh.NewServerConn(conn, config)

should be EDIT

  1. sshproxyconn := &amp;SshProxyConn{conn, time.Second * 20}
  2. Conn, chans, reqs, err := ssh.NewServerConn(sshproxyconn , config)

huangapple
  • 本文由 发表于 2022年9月22日 19:56:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/73814237.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定