From 94b6eec5dc639e87f0e2f739cfd257a432160881 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Roman=20Koll=C3=A1r?= <roman.kollar.0@gmail.com>
Date: Thu, 21 Nov 2019 22:25:52 +0000
Subject: [PATCH] [release-branch.go1.13] net/http: fix Server.ConnContext
 modifying context for all new connections

Updates #35750
Fixes #35765

Change-Id: I65d38cfc5ddd66131777e104c269cc3559b2471d
GitHub-Last-Rev: 953fdfd49b2be665be43f8148d2a6180dae3b91c
GitHub-Pull-Request: golang/go#35751
Reviewed-on: https://go-review.googlesource.com/c/go/+/208318
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
(cherry picked from commit bbbc6589dfbc05be2bfa59f51c20f9eaa8d0c531)
Reviewed-on: https://go-review.googlesource.com/c/go/+/208235
Reviewed-by: Bryan C. Mills <bcmills@google.com>
---
 src/net/http/serve_test.go | 33 +++++++++++++++++++++++++++++++++
 src/net/http/server.go     |  7 ++++---
 2 files changed, 37 insertions(+), 3 deletions(-)

diff --git a/src/net/http/serve_test.go b/src/net/http/serve_test.go
index 1d1449aa65..90f112b2ee 100644
--- a/src/net/http/serve_test.go
+++ b/src/net/http/serve_test.go
@@ -6121,6 +6121,39 @@ func TestServerContextsHTTP2(t *testing.T) {
 	}
 }
 
+// Issue 35750: check ConnContext not modifying context for other connections
+func TestConnContextNotModifyingAllContexts(t *testing.T) {
+	setParallel(t)
+	defer afterTest(t)
+	type connKey struct{}
+	ts := httptest.NewUnstartedServer(HandlerFunc(func(rw ResponseWriter, r *Request) {
+		rw.Header().Set("Connection", "close")
+	}))
+	ts.Config.ConnContext = func(ctx context.Context, c net.Conn) context.Context {
+		if got := ctx.Value(connKey{}); got != nil {
+			t.Errorf("in ConnContext, unexpected context key = %#v", got)
+		}
+		return context.WithValue(ctx, connKey{}, "conn")
+	}
+	ts.Start()
+	defer ts.Close()
+
+	var res *Response
+	var err error
+
+	res, err = ts.Client().Get(ts.URL)
+	if err != nil {
+		t.Fatal(err)
+	}
+	res.Body.Close()
+
+	res, err = ts.Client().Get(ts.URL)
+	if err != nil {
+		t.Fatal(err)
+	}
+	res.Body.Close()
+}
+
 // Issue 30710: ensure that as per the spec, a server responds
 // with 501 Not Implemented for unsupported transfer-encodings.
 func TestUnsupportedTransferEncodingsReturn501(t *testing.T) {
diff --git a/src/net/http/server.go b/src/net/http/server.go
index 95a5eabaa2..8252e45aca 100644
--- a/src/net/http/server.go
+++ b/src/net/http/server.go
@@ -2915,16 +2915,17 @@ func (srv *Server) Serve(l net.Listener) error {
 			}
 			return e
 		}
+		connCtx := ctx
 		if cc := srv.ConnContext; cc != nil {
-			ctx = cc(ctx, rw)
-			if ctx == nil {
+			connCtx = cc(connCtx, rw)
+			if connCtx == nil {
 				panic("ConnContext returned nil")
 			}
 		}
 		tempDelay = 0
 		c := srv.newConn(rw)
 		c.setState(c.rwc, StateNew) // before Serve can return
-		go c.serve(ctx)
+		go c.serve(connCtx)
 	}
 }
 
-- 
2.17.1

