From dc200e139cfec5d3e9662c004aaf47f083ba5036 Mon Sep 17 00:00:00 2001 From: WeidiDeng Date: Tue, 9 Sep 2025 11:29:22 +0800 Subject: [PATCH] extract custom connection and tls connection state if available --- modules/caddyhttp/app.go | 16 +++++++++++++++- modules/caddyhttp/server.go | 16 +++++++--------- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/modules/caddyhttp/app.go b/modules/caddyhttp/app.go index 17fb4d0d5..a20738fad 100644 --- a/modules/caddyhttp/app.go +++ b/modules/caddyhttp/app.go @@ -466,7 +466,21 @@ func (app *App) Start() error { ErrorLog: serverLogger, Protocols: new(http.Protocols), ConnContext: func(ctx context.Context, c net.Conn) context.Context { - return context.WithValue(ctx, ConnCtxKey, c) + if nc, ok := c.(interface{ tlsNetConn() net.Conn }); ok { + var ( + tlsConState *tls.ConnectionState + getTlsConStateFunc = func() *tls.ConnectionState { + if tlsConState != nil { + return tlsConState + } + tlsConStateVal := nc.tlsNetConn().(connectionStater).ConnectionState() + tlsConState = &tlsConStateVal + return tlsConState + } + ) + ctx = context.WithValue(ctx, tlsConnectionStateFuncCtxKey, getTlsConStateFunc) + } + return ctx }, } diff --git a/modules/caddyhttp/server.go b/modules/caddyhttp/server.go index c195857ba..ac30f4028 100644 --- a/modules/caddyhttp/server.go +++ b/modules/caddyhttp/server.go @@ -288,14 +288,9 @@ type Server struct { // ServeHTTP is the entry point for all HTTP requests. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { // If there are listener wrappers that process tls connections but don't return a *tls.Conn, this field will be nil. - // TODO: Scheduled to be removed later because https://github.com/golang/go/pull/56110 has been merged. if r.TLS == nil { - // not all requests have a conn (like virtual requests) - see #5698 - if conn, ok := r.Context().Value(ConnCtxKey).(net.Conn); ok { - if csc, ok := conn.(connectionStater); ok { - r.TLS = new(tls.ConnectionState) - *r.TLS = csc.ConnectionState() - } + if tlsConnStateFunc, ok := r.Context().Value(tlsConnectionStateFuncCtxKey).(func() *tls.ConnectionState); ok { + r.TLS = tlsConnStateFunc() } } @@ -1115,11 +1110,14 @@ const ( // originally came into the server's entry handler OriginalRequestCtxKey caddy.CtxKey = "original_request" - // For referencing underlying net.Conn - // This will eventually be deprecated and not used. To refer to the underlying connection, implement a middleware plugin + // DEPRECATED: not used anymore. + // To refer to the underlying connection, implement a middleware plugin // that RegisterConnContext during provisioning. ConnCtxKey caddy.CtxKey = "conn" + // used to get the tls connection state in the context, if available + tlsConnectionStateFuncCtxKey caddy.CtxKey = "tls_connection_state_func" + // For tracking whether the client is a trusted proxy TrustedProxyVarKey string = "trusted_proxy"