Skip to content

net/http: Server.ConnContext accidentally modifies context for all connections #35750

Closed
@rkollar

Description

@rkollar

What version of Go are you using (go version)?

$ go version
go version go1.13.4 linux/amd64

Does this issue reproduce with the latest release?

Yes.

What did you do?

Docs of ConnContext say that:

ConnContext optionally specifies a function that modifies the context used for a new connection c.

However, it assigns this new context to a variable shared between connections in the accept loop. Thus creating a growing chain of contexts.

Example code:

package main

import (
	"context"
	"fmt"
	"net"
	"net/http"
)

func main() {
	server := &http.Server{
		Addr: ":4444",
		Handler: http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
			rw.Header().Set("Connection", "close")
		}),
		ConnContext: func(ctx context.Context, c net.Conn) context.Context {
			fmt.Printf("conn: %s\n", c.RemoteAddr())

			if c2 := ctx.Value("conn"); c2 != nil {
				fmt.Printf("existing: %s\n", c2.(net.Conn).RemoteAddr())
			}

			return context.WithValue(ctx, "conn", c)
		},
	}
	go func() {
		panic(server.ListenAndServe())
	}()

	var err error

	fmt.Printf("\nrequest 1:\n")
	_, err = http.Get("http://localhost:4444/")
	if err != nil {
		panic(err)
	}
	fmt.Printf("request 1 done\n")

	fmt.Printf("\nrequest 2:\n")
	_, err = http.Get("http://localhost:4444/")
	if err != nil {
		panic(err)
	}
	fmt.Printf("request 2 done\n")
}

What did you expect to see?

request 1:
conn: [::1]:34022
request 1 done

request 2:
conn: [::1]:34024
request 2 done

What did you see instead?

request 1:
conn: [::1]:34022
request 1 done

request 2:
conn: [::1]:34024
existing: [::1]:34022
request 2 done

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeNeedsFixThe path to resolution is known, but the work has not been done.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions