From 1141698a92c70fbd08edc4370815612b4e5766ad Mon Sep 17 00:00:00 2001 From: Simon Ser Date: Tue, 18 Feb 2020 17:26:17 +0100 Subject: [PATCH] Enable TCP keep-alive on all connections --- server.go | 17 +++++++++++++++++ upstream.go | 2 ++ 2 files changed, 19 insertions(+) diff --git a/server.go b/server.go index e3a6ff6..7777040 100644 --- a/server.go +++ b/server.go @@ -5,10 +5,25 @@ import ( "log" "net" "sync" + "time" "gopkg.in/irc.v3" ) +// TODO: make configurable +var keepAlivePeriod = time.Minute + +func setKeepAlive(c net.Conn) error { + tcpConn, ok := c.(*net.TCPConn) + if !ok { + return fmt.Errorf("cannot enable keep-alive on a non-TCP connection") + } + if err := tcpConn.SetKeepAlive(true); err != nil { + return err + } + return tcpConn.SetKeepAlivePeriod(keepAlivePeriod) +} + type Logger interface { Print(v ...interface{}) Printf(format string, v ...interface{}) @@ -177,6 +192,8 @@ func (s *Server) Serve(ln net.Listener) error { return fmt.Errorf("failed to accept connection: %v", err) } + setKeepAlive(netConn) + dc := newDownstreamConn(s, netConn) go func() { s.lock.Lock() diff --git a/upstream.go b/upstream.go index f8b9ac2..a21f6c8 100644 --- a/upstream.go +++ b/upstream.go @@ -56,6 +56,8 @@ func connectToUpstream(u *user, upstream *Upstream) (*upstreamConn, error) { return nil, fmt.Errorf("failed to dial %q: %v", upstream.Addr, err) } + setKeepAlive(netConn) + msgs := make(chan *irc.Message, 64) uc := &upstreamConn{ upstream: upstream,