From 8affb6210e1531f51ae2cf2cd631e0bbe2e7e95a Mon Sep 17 00:00:00 2001 From: Reese Norris Date: Sun, 6 Jul 2025 17:40:11 -0700 Subject: [PATCH] add client timeout via net/Conn SetDeadline --- fsd/client.go | 2 ++ fsd/conn.go | 4 +++- fsd/env.go | 3 +++ fsd/util.go | 6 ++++++ 4 files changed, 14 insertions(+), 1 deletion(-) diff --git a/fsd/client.go b/fsd/client.go index 3441fe8..b3c8247 100644 --- a/fsd/client.go +++ b/fsd/client.go @@ -108,6 +108,8 @@ func (s *Server) eventLoop(client *Client) { go client.senderWorker() for { + // Set deadline and attempt to read + client.conn.SetReadDeadline(getTimeBySecondsInFuture(s.cfg.ConnectionTimeoutSeconds)) if !client.scanner.Scan() { return } diff --git a/fsd/conn.go b/fsd/conn.go index 41ae4d1..4cb351e 100644 --- a/fsd/conn.go +++ b/fsd/conn.go @@ -35,9 +35,11 @@ func (s *Server) handleConn(ctx context.Context, conn net.Conn) { fmt.Println(err) } }() - defer conn.Close() + // Set timeout for login phase + conn.SetDeadline(getTimeBySecondsInFuture(s.cfg.ConnectionTimeoutSeconds)) + if err := sendServerIdent(conn); err != nil { fmt.Printf("Error sending server ident: %v\n", err) return diff --git a/fsd/env.go b/fsd/env.go index b4befc1..fd32fbf 100644 --- a/fsd/env.go +++ b/fsd/env.go @@ -16,6 +16,9 @@ type ServerConfig struct { NumMetarWorkers int `env:"NUM_METAR_WORKERS, default=4"` // Number of METAR fetch workers to run ServiceHTTPListenAddr string `env:"SERVICE_HTTP_LISTEN_ADDR, default=:13618"` + + // Seconds after which a connection will be closed for inactivity + ConnectionTimeoutSeconds int `env:"CONNECTION_TIMEOUT_SECONDS, default=30"` } func loadServerConfig(ctx context.Context) (config *ServerConfig, err error) { diff --git a/fsd/util.go b/fsd/util.go index 8629527..692c243 100644 --- a/fsd/util.go +++ b/fsd/util.go @@ -7,6 +7,7 @@ import ( "slices" "strconv" "strings" + "time" ) // FSD error codes @@ -418,3 +419,8 @@ func sendSendFastPacket(client *Client, enabled bool) { client.send(builder.String()) } + +// getTimeBySecondsInFuture returns time.Now + seconds +func getTimeBySecondsInFuture(seconds int) time.Time { + return time.Now().Add(time.Duration(seconds) * time.Second) +}