| 1 |
package runtime |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"net" |
| 6 |
"net/http" |
| 7 |
"strconv" |
| 8 |
"strings" |
| 9 |
"time" |
| 10 |
|
| 11 |
"golang.org/x/net/context" |
| 12 |
"google.golang.org/grpc/codes" |
| 13 |
"google.golang.org/grpc/grpclog" |
| 14 |
"google.golang.org/grpc/metadata" |
| 15 |
"google.golang.org/grpc/status" |
| 16 |
) |
| 17 |
|
| 18 |
// MetadataHeaderPrefix is the http prefix that represents custom metadata |
| 19 |
// parameters to or from a gRPC call. |
| 20 |
const MetadataHeaderPrefix = "Grpc-Metadata-" |
| 21 |
|
| 22 |
// MetadataPrefix is the prefix for grpc-gateway supplied custom metadata fields. |
| 23 |
const MetadataPrefix = "grpcgateway-" |
| 24 |
|
| 25 |
// MetadataTrailerPrefix is prepended to gRPC metadata as it is converted to |
| 26 |
// HTTP headers in a response handled by grpc-gateway |
| 27 |
const MetadataTrailerPrefix = "Grpc-Trailer-" |
| 28 |
|
| 29 |
const metadataGrpcTimeout = "Grpc-Timeout" |
| 30 |
|
| 31 |
const xForwardedFor = "X-Forwarded-For" |
| 32 |
const xForwardedHost = "X-Forwarded-Host" |
| 33 |
|
| 34 |
var ( |
| 35 |
// DefaultContextTimeout is used for gRPC call context.WithTimeout whenever a Grpc-Timeout inbound |
| 36 |
// header isn't present. If the value is 0 the sent `context` will not have a timeout. |
| 37 |
DefaultContextTimeout = 0 * time.Second |
| 38 |
) |
| 39 |
|
| 40 |
/* |
| 41 |
AnnotateContext adds context information such as metadata from the request. |
| 42 |
|
| 43 |
At a minimum, the RemoteAddr is included in the fashion of "X-Forwarded-For", |
| 44 |
except that the forwarded destination is not another HTTP service but rather |
| 45 |
a gRPC service. |
| 46 |
*/ |
| 47 |
func AnnotateContext(ctx context.Context, mux *ServeMux, req *http.Request) (context.Context, error) { |
| 48 |
var pairs []string |
| 49 |
timeout := DefaultContextTimeout |
| 50 |
if tm := req.Header.Get(metadataGrpcTimeout); tm != "" { |
| 51 |
var err error |
| 52 |
timeout, err = timeoutDecode(tm) |
| 53 |
if err != nil { |
| 54 |
return nil, status.Errorf(codes.InvalidArgument, "invalid grpc-timeout: %s", tm) |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
for key, vals := range req.Header { |
| 59 |
for _, val := range vals { |
| 60 |
// For backwards-compatibility, pass through 'authorization' header with no prefix. |
| 61 |
if strings.ToLower(key) == "authorization" { |
| 62 |
pairs = append(pairs, "authorization", val) |
| 63 |
} |
| 64 |
if h, ok := mux.incomingHeaderMatcher(key); ok { |
| 65 |
pairs = append(pairs, h, val) |
| 66 |
} |
| 67 |
} |
| 68 |
} |
| 69 |
if host := req.Header.Get(xForwardedHost); host != "" { |
| 70 |
pairs = append(pairs, strings.ToLower(xForwardedHost), host) |
| 71 |
} else if req.Host != "" { |
| 72 |
pairs = append(pairs, strings.ToLower(xForwardedHost), req.Host) |
| 73 |
} |
| 74 |
|
| 75 |
if addr := req.RemoteAddr; addr != "" { |
| 76 |
if remoteIP, _, err := net.SplitHostPort(addr); err == nil { |
| 77 |
if fwd := req.Header.Get(xForwardedFor); fwd == "" { |
| 78 |
pairs = append(pairs, strings.ToLower(xForwardedFor), remoteIP) |
| 79 |
} else { |
| 80 |
pairs = append(pairs, strings.ToLower(xForwardedFor), fmt.Sprintf("%s, %s", fwd, remoteIP)) |
| 81 |
} |
| 82 |
} else { |
| 83 |
grpclog.Printf("invalid remote addr: %s", addr) |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
if timeout != 0 { |
| 88 |
ctx, _ = context.WithTimeout(ctx, timeout) |
| 89 |
} |
| 90 |
if len(pairs) == 0 { |
| 91 |
return ctx, nil |
| 92 |
} |
| 93 |
md := metadata.Pairs(pairs...) |
| 94 |
if mux.metadataAnnotator != nil { |
| 95 |
md = metadata.Join(md, mux.metadataAnnotator(ctx, req)) |
| 96 |
} |
| 97 |
return metadata.NewOutgoingContext(ctx, md), nil |
| 98 |
} |
| 99 |
|
| 100 |
// ServerMetadata consists of metadata sent from gRPC server. |
| 101 |
type ServerMetadata struct { |
| 102 |
HeaderMD metadata.MD |
| 103 |
TrailerMD metadata.MD |
| 104 |
} |
| 105 |
|
| 106 |
type serverMetadataKey struct{} |
| 107 |
|
| 108 |
// NewServerMetadataContext creates a new context with ServerMetadata |
| 109 |
func NewServerMetadataContext(ctx context.Context, md ServerMetadata) context.Context { |
| 110 |
return context.WithValue(ctx, serverMetadataKey{}, md) |
| 111 |
} |
| 112 |
|
| 113 |
// ServerMetadataFromContext returns the ServerMetadata in ctx |
| 114 |
func ServerMetadataFromContext(ctx context.Context) (md ServerMetadata, ok bool) { |
| 115 |
md, ok = ctx.Value(serverMetadataKey{}).(ServerMetadata) |
| 116 |
return |
| 117 |
} |
| 118 |
|
| 119 |
func timeoutDecode(s string) (time.Duration, error) { |
| 120 |
size := len(s) |
| 121 |
if size < 2 { |
| 122 |
return 0, fmt.Errorf("timeout string is too short: %q", s) |
| 123 |
} |
| 124 |
d, ok := timeoutUnitToDuration(s[size-1]) |
| 125 |
if !ok { |
| 126 |
return 0, fmt.Errorf("timeout unit is not recognized: %q", s) |
| 127 |
} |
| 128 |
t, err := strconv.ParseInt(s[:size-1], 10, 64) |
| 129 |
if err != nil { |
| 130 |
return 0, err |
| 131 |
} |
| 132 |
return d * time.Duration(t), nil |
| 133 |
} |
| 134 |
|
| 135 |
func timeoutUnitToDuration(u uint8) (d time.Duration, ok bool) { |
| 136 |
switch u { |
| 137 |
case 'H': |
| 138 |
return time.Hour, true |
| 139 |
case 'M': |
| 140 |
return time.Minute, true |
| 141 |
case 'S': |
| 142 |
return time.Second, true |
| 143 |
case 'm': |
| 144 |
return time.Millisecond, true |
| 145 |
case 'u': |
| 146 |
return time.Microsecond, true |
| 147 |
case 'n': |
| 148 |
return time.Nanosecond, true |
| 149 |
default: |
| 150 |
} |
| 151 |
return |
| 152 |
} |
| 153 |
|
| 154 |
// isPermanentHTTPHeader checks whether hdr belongs to the list of |
| 155 |
// permenant request headers maintained by IANA. |
| 156 |
// http://www.iana.org/assignments/message-headers/message-headers.xml |
| 157 |
func isPermanentHTTPHeader(hdr string) bool { |
| 158 |
switch hdr { |
| 159 |
case |
| 160 |
"Accept", |
| 161 |
"Accept-Charset", |
| 162 |
"Accept-Language", |
| 163 |
"Accept-Ranges", |
| 164 |
"Authorization", |
| 165 |
"Cache-Control", |
| 166 |
"Content-Type", |
| 167 |
"Cookie", |
| 168 |
"Date", |
| 169 |
"Expect", |
| 170 |
"From", |
| 171 |
"Host", |
| 172 |
"If-Match", |
| 173 |
"If-Modified-Since", |
| 174 |
"If-None-Match", |
| 175 |
"If-Schedule-Tag-Match", |
| 176 |
"If-Unmodified-Since", |
| 177 |
"Max-Forwards", |
| 178 |
"Origin", |
| 179 |
"Pragma", |
| 180 |
"Referer", |
| 181 |
"User-Agent", |
| 182 |
"Via", |
| 183 |
"Warning": |
| 184 |
return true |
| 185 |
} |
| 186 |
return false |
| 187 |
} |