2021-01-20 18:03:05 +00:00
|
|
|
package http
|
2021-01-04 16:52:21 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2021-02-10 20:26:45 +00:00
|
|
|
"crypto/tls"
|
2021-01-04 16:52:21 +00:00
|
|
|
"net"
|
2021-02-10 20:26:45 +00:00
|
|
|
|
|
|
|
"github.com/soheilhy/cmux"
|
2021-01-04 16:52:21 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type httpContextKey string
|
|
|
|
|
|
|
|
const (
|
2021-01-20 18:03:05 +00:00
|
|
|
remoteAddrKey httpContextKey = "gitlab.com/inetmock/inetmock/internal/endpoint/handler/http/context/remoteAddr"
|
|
|
|
localAddrKey httpContextKey = "gitlab.com/inetmock/inetmock/internal/endpoint/handler/http/context/localAddr"
|
2021-02-10 20:26:45 +00:00
|
|
|
tlsStateKey httpContextKey = "gitlab.com/inetmock/inetmock/internal/endpoint/handler/http/context/tlsState"
|
2021-01-04 16:52:21 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func StoreConnPropertiesInContext(ctx context.Context, c net.Conn) context.Context {
|
|
|
|
ctx = context.WithValue(ctx, remoteAddrKey, c.RemoteAddr())
|
|
|
|
ctx = context.WithValue(ctx, localAddrKey, c.LocalAddr())
|
2021-02-10 20:26:45 +00:00
|
|
|
ctx = addTLSConnectionStateToContext(ctx, c)
|
2021-01-04 16:52:21 +00:00
|
|
|
return ctx
|
|
|
|
}
|
|
|
|
|
2021-02-10 20:26:45 +00:00
|
|
|
func addTLSConnectionStateToContext(ctx context.Context, c net.Conn) context.Context {
|
|
|
|
switch subConn := c.(type) {
|
|
|
|
case *tls.Conn:
|
|
|
|
return context.WithValue(ctx, tlsStateKey, subConn.ConnectionState())
|
|
|
|
case *cmux.MuxConn:
|
|
|
|
return addTLSConnectionStateToContext(ctx, subConn.Conn)
|
|
|
|
default:
|
|
|
|
return ctx
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func tlsConnectionState(ctx context.Context) (tls.ConnectionState, bool) {
|
|
|
|
val := ctx.Value(tlsStateKey)
|
|
|
|
if val == nil {
|
|
|
|
return tls.ConnectionState{}, false
|
|
|
|
}
|
|
|
|
return val.(tls.ConnectionState), true
|
|
|
|
}
|
|
|
|
|
2021-01-20 18:03:05 +00:00
|
|
|
func localAddr(ctx context.Context) net.Addr {
|
2021-01-04 16:52:21 +00:00
|
|
|
val := ctx.Value(localAddrKey)
|
|
|
|
if val == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return val.(net.Addr)
|
|
|
|
}
|
|
|
|
|
2021-01-20 18:03:05 +00:00
|
|
|
func remoteAddr(ctx context.Context) net.Addr {
|
2021-01-04 16:52:21 +00:00
|
|
|
val := ctx.Value(remoteAddrKey)
|
|
|
|
if val == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return val.(net.Addr)
|
|
|
|
}
|