Skip to content

Commit

Permalink
fix: memory leak on http tunnel
Browse files Browse the repository at this point in the history
  • Loading branch information
nange committed Mar 14, 2023
1 parent af7f016 commit 749cfae
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
9 changes: 8 additions & 1 deletion httptunnel/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ func (s *Server) push(w http.ResponseWriter, r *http.Request) {
s.Lock()
conn, ok := s.connMap[reqID]
if !ok {
conn = NewServerConn()
conn = NewServerConn(reqID, s.CloseConn)
s.connMap[reqID] = conn
s.connCh <- conn
}
Expand All @@ -162,6 +162,13 @@ func (s *Server) push(w http.ResponseWriter, r *http.Request) {
writeNoContent(w)
}

func (s *Server) CloseConn(reqID string) {
s.Lock()
defer s.Unlock()
s.connMap[reqID] = nil
delete(s.connMap, reqID)
}

func writeNotFoundError(w http.ResponseWriter) {
http.Error(w, "404 NOT FOUND", http.StatusNotFound)
}
Expand Down
16 changes: 13 additions & 3 deletions httptunnel/server_conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,20 @@ import (
var _ net.Conn = (*ServerConn)(nil)

type ServerConn struct {
reqID string
closeConn func(reqID string)

local net.Conn
remote net.Conn
}

func NewServerConn() *ServerConn {
func NewServerConn(reqID string, closeConn func(reqID string)) *ServerConn {
read, write := net.Pipe()
return &ServerConn{
local: read,
remote: write,
reqID: reqID,
closeConn: closeConn,
local: read,
remote: write,
}
}

Expand All @@ -37,6 +42,11 @@ func (c *ServerConn) Write(b []byte) (n int, err error) {
}

func (c *ServerConn) Close() error {
if c.closeConn != nil {
c.closeConn(c.reqID)
}
c.closeConn = nil

return c.remote.Close()
}

Expand Down

0 comments on commit 749cfae

Please sign in to comment.