3
* Copyright 2014 gRPC authors.
5
* Licensed under the Apache License, Version 2.0 (the "License");
6
* you may not use this file except in compliance with the License.
7
* You may obtain a copy of the License at
9
* http://www.apache.org/licenses/LICENSE-2.0
11
* Unless required by applicable law or agreed to in writing, software
12
* distributed under the License is distributed on an "AS IS" BASIS,
13
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
* See the License for the specific language governing permissions and
15
* limitations under the License.
36
"github.com/golang/protobuf/proto"
37
"golang.org/x/net/http2"
38
"golang.org/x/net/http2/hpack"
39
spb "google.golang.org/genproto/googleapis/rpc/status"
40
"google.golang.org/grpc/codes"
41
"google.golang.org/grpc/grpclog"
42
"google.golang.org/grpc/internal/grpcutil"
43
"google.golang.org/grpc/status"
47
// http2MaxFrameLen specifies the max length of a HTTP2 frame.
48
http2MaxFrameLen = 16384 // 16KB frame
49
// http://http2.github.io/http2-spec/#SettingValues
50
http2InitHeaderTableSize = 4096
51
// baseContentType is the base content-type for gRPC. This is a valid
52
// content-type on it's own, but can also include a content-subtype such as
53
// "proto" as a suffix after "+" or ";". See
54
// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests
60
clientPreface = []byte(http2.ClientPreface)
61
http2ErrConvTab = map[http2.ErrCode]codes.Code{
62
http2.ErrCodeNo: codes.Internal,
63
http2.ErrCodeProtocol: codes.Internal,
64
http2.ErrCodeInternal: codes.Internal,
65
http2.ErrCodeFlowControl: codes.ResourceExhausted,
66
http2.ErrCodeSettingsTimeout: codes.Internal,
67
http2.ErrCodeStreamClosed: codes.Internal,
68
http2.ErrCodeFrameSize: codes.Internal,
69
http2.ErrCodeRefusedStream: codes.Unavailable,
70
http2.ErrCodeCancel: codes.Canceled,
71
http2.ErrCodeCompression: codes.Internal,
72
http2.ErrCodeConnect: codes.Internal,
73
http2.ErrCodeEnhanceYourCalm: codes.ResourceExhausted,
74
http2.ErrCodeInadequateSecurity: codes.PermissionDenied,
75
http2.ErrCodeHTTP11Required: codes.Internal,
77
// HTTPStatusConvTab is the HTTP status code to gRPC error code conversion table.
78
HTTPStatusConvTab = map[int]codes.Code{
79
// 400 Bad Request - INTERNAL.
80
http.StatusBadRequest: codes.Internal,
81
// 401 Unauthorized - UNAUTHENTICATED.
82
http.StatusUnauthorized: codes.Unauthenticated,
83
// 403 Forbidden - PERMISSION_DENIED.
84
http.StatusForbidden: codes.PermissionDenied,
85
// 404 Not Found - UNIMPLEMENTED.
86
http.StatusNotFound: codes.Unimplemented,
87
// 429 Too Many Requests - UNAVAILABLE.
88
http.StatusTooManyRequests: codes.Unavailable,
89
// 502 Bad Gateway - UNAVAILABLE.
90
http.StatusBadGateway: codes.Unavailable,
91
// 503 Service Unavailable - UNAVAILABLE.
92
http.StatusServiceUnavailable: codes.Unavailable,
93
// 504 Gateway timeout - UNAVAILABLE.
94
http.StatusGatewayTimeout: codes.Unavailable,
96
logger = grpclog.Component("transport")
99
type parsedHeaderData struct {
101
// statusGen caches the stream status received from the trailer the server
102
// sent. Client side only. Do not access directly. After all trailers are
103
// parsed, use the status method to retrieve the status.
104
statusGen *status.Status
105
// rawStatusCode and rawStatusMsg are set from the raw trailer fields and are not
106
// intended for direct access outside of parsing.
110
// Server side only fields.
112
timeout time.Duration
114
// key-value metadata map from the peer.
115
mdata map[string][]string
118
contentSubtype string
120
// isGRPC field indicates whether the peer is speaking gRPC (otherwise HTTP).
122
// We are in gRPC mode (peer speaking gRPC) if:
123
// * We are client side and have already received a HEADER frame that indicates gRPC peer.
124
// * The header contains valid a content-type, i.e. a string starts with "application/grpc"
125
// And we should handle error specific to gRPC.
127
// Otherwise (i.e. a content-type string starts without "application/grpc", or does not exist), we
128
// are in HTTP fallback mode, and should handle error specific to HTTP.
132
contentTypeErr string
135
// decodeState configures decoding criteria and records the decoded data.
136
type decodeState struct {
137
// whether decoding on server side or not
140
// Records the states during HPACK decoding. It will be filled with info parsed from HTTP HEADERS
141
// frame once decodeHeader function has been invoked and returned.
142
data parsedHeaderData
145
// isReservedHeader checks whether hdr belongs to HTTP2 headers
146
// reserved by gRPC protocol. Any other headers are classified as the
147
// user-specified metadata.
148
func isReservedHeader(hdr string) bool {
149
if hdr != "" && hdr[0] == ':' {
160
"grpc-status-details-bin",
161
// Intentionally exclude grpc-previous-rpc-attempts and
162
// grpc-retry-pushback-ms, which are "reserved", but their API
163
// intentionally works via metadata.
171
// isWhitelistedHeader checks whether hdr should be propagated into metadata
172
// visible to users, even though it is classified as "reserved", above.
173
func isWhitelistedHeader(hdr string) bool {
175
case ":authority", "user-agent":
182
func (d *decodeState) status() *status.Status {
183
if d.data.statusGen == nil {
184
// No status-details were provided; generate status using code/msg.
185
d.data.statusGen = status.New(codes.Code(int32(*(d.data.rawStatusCode))), d.data.rawStatusMsg)
187
return d.data.statusGen
190
const binHdrSuffix = "-bin"
192
func encodeBinHeader(v []byte) string {
193
return base64.RawStdEncoding.EncodeToString(v)
196
func decodeBinHeader(v string) ([]byte, error) {
198
// Input was padded, or padding was not necessary.
199
return base64.StdEncoding.DecodeString(v)
201
return base64.RawStdEncoding.DecodeString(v)
204
func encodeMetadataHeader(k, v string) string {
205
if strings.HasSuffix(k, binHdrSuffix) {
206
return encodeBinHeader(([]byte)(v))
211
func decodeMetadataHeader(k, v string) (string, error) {
212
if strings.HasSuffix(k, binHdrSuffix) {
213
b, err := decodeBinHeader(v)
214
return string(b), err
219
func (d *decodeState) decodeHeader(frame *http2.MetaHeadersFrame) (http2.ErrCode, error) {
220
// frame.Truncated is set to true when framer detects that the current header
221
// list size hits MaxHeaderListSize limit.
223
return http2.ErrCodeFrameSize, status.Error(codes.Internal, "peer header list size exceeded limit")
226
for _, hf := range frame.Fields {
227
d.processHeaderField(hf)
231
if d.data.grpcErr != nil {
232
return http2.ErrCodeProtocol, d.data.grpcErr
235
return http2.ErrCodeNo, nil
237
if d.data.rawStatusCode == nil && d.data.statusGen == nil {
238
// gRPC status doesn't exist.
239
// Set rawStatusCode to be unknown and return nil error.
240
// So that, if the stream has ended this Unknown status
241
// will be propagated to the user.
242
// Otherwise, it will be ignored. In which case, status from
243
// a later trailer, that has StreamEnded flag set, is propagated.
244
code := int(codes.Unknown)
245
d.data.rawStatusCode = &code
247
return http2.ErrCodeNo, nil
250
// HTTP fallback mode
251
if d.data.httpErr != nil {
252
return http2.ErrCodeProtocol, d.data.httpErr
256
code = codes.Internal // when header does not include HTTP status, return INTERNAL
260
if d.data.httpStatus != nil {
261
code, ok = HTTPStatusConvTab[*(d.data.httpStatus)]
267
return http2.ErrCodeProtocol, status.Error(code, d.constructHTTPErrMsg())
270
// constructErrMsg constructs error message to be returned in HTTP fallback mode.
271
// Format: HTTP status code and its corresponding message + content-type error message.
272
func (d *decodeState) constructHTTPErrMsg() string {
275
if d.data.httpStatus == nil {
276
errMsgs = append(errMsgs, "malformed header: missing HTTP status")
278
errMsgs = append(errMsgs, fmt.Sprintf("%s: HTTP status code %d", http.StatusText(*(d.data.httpStatus)), *d.data.httpStatus))
281
if d.data.contentTypeErr == "" {
282
errMsgs = append(errMsgs, "transport: missing content-type field")
284
errMsgs = append(errMsgs, d.data.contentTypeErr)
287
return strings.Join(errMsgs, "; ")
290
func (d *decodeState) addMetadata(k, v string) {
291
if d.data.mdata == nil {
292
d.data.mdata = make(map[string][]string)
294
d.data.mdata[k] = append(d.data.mdata[k], v)
297
func (d *decodeState) processHeaderField(f hpack.HeaderField) {
300
contentSubtype, validContentType := grpcutil.ContentSubtype(f.Value)
301
if !validContentType {
302
d.data.contentTypeErr = fmt.Sprintf("transport: received the unexpected content-type %q", f.Value)
305
d.data.contentSubtype = contentSubtype
306
// TODO: do we want to propagate the whole content-type in the metadata,
307
// or come up with a way to just propagate the content-subtype if it was set?
308
// ie {"content-type": "application/grpc+proto"} or {"content-subtype": "proto"}
310
d.addMetadata(f.Name, f.Value)
312
case "grpc-encoding":
313
d.data.encoding = f.Value
315
code, err := strconv.Atoi(f.Value)
317
d.data.grpcErr = status.Errorf(codes.Internal, "transport: malformed grpc-status: %v", err)
320
d.data.rawStatusCode = &code
322
d.data.rawStatusMsg = decodeGrpcMessage(f.Value)
323
case "grpc-status-details-bin":
324
v, err := decodeBinHeader(f.Value)
326
d.data.grpcErr = status.Errorf(codes.Internal, "transport: malformed grpc-status-details-bin: %v", err)
330
if err := proto.Unmarshal(v, s); err != nil {
331
d.data.grpcErr = status.Errorf(codes.Internal, "transport: malformed grpc-status-details-bin: %v", err)
334
d.data.statusGen = status.FromProto(s)
336
d.data.timeoutSet = true
338
if d.data.timeout, err = decodeTimeout(f.Value); err != nil {
339
d.data.grpcErr = status.Errorf(codes.Internal, "transport: malformed time-out: %v", err)
342
d.data.method = f.Value
344
code, err := strconv.Atoi(f.Value)
346
d.data.httpErr = status.Errorf(codes.Internal, "transport: malformed http-status: %v", err)
349
d.data.httpStatus = &code
350
case "grpc-tags-bin":
351
v, err := decodeBinHeader(f.Value)
353
d.data.grpcErr = status.Errorf(codes.Internal, "transport: malformed grpc-tags-bin: %v", err)
357
d.addMetadata(f.Name, string(v))
358
case "grpc-trace-bin":
359
v, err := decodeBinHeader(f.Value)
361
d.data.grpcErr = status.Errorf(codes.Internal, "transport: malformed grpc-trace-bin: %v", err)
364
d.data.statsTrace = v
365
d.addMetadata(f.Name, string(v))
367
if isReservedHeader(f.Name) && !isWhitelistedHeader(f.Name) {
370
v, err := decodeMetadataHeader(f.Name, f.Value)
372
if logger.V(logLevel) {
373
logger.Errorf("Failed to decode metadata header (%q, %q): %v", f.Name, f.Value, err)
377
d.addMetadata(f.Name, v)
381
type timeoutUnit uint8
384
hour timeoutUnit = 'H'
385
minute timeoutUnit = 'M'
386
second timeoutUnit = 'S'
387
millisecond timeoutUnit = 'm'
388
microsecond timeoutUnit = 'u'
389
nanosecond timeoutUnit = 'n'
392
func timeoutUnitToDuration(u timeoutUnit) (d time.Duration, ok bool) {
395
return time.Hour, true
397
return time.Minute, true
399
return time.Second, true
401
return time.Millisecond, true
403
return time.Microsecond, true
405
return time.Nanosecond, true
411
func decodeTimeout(s string) (time.Duration, error) {
414
return 0, fmt.Errorf("transport: timeout string is too short: %q", s)
417
// Spec allows for 8 digits plus the unit.
418
return 0, fmt.Errorf("transport: timeout string is too long: %q", s)
420
unit := timeoutUnit(s[size-1])
421
d, ok := timeoutUnitToDuration(unit)
423
return 0, fmt.Errorf("transport: timeout unit is not recognized: %q", s)
425
t, err := strconv.ParseInt(s[:size-1], 10, 64)
429
const maxHours = math.MaxInt64 / int64(time.Hour)
430
if d == time.Hour && t > maxHours {
431
// This timeout would overflow math.MaxInt64; clamp it.
432
return time.Duration(math.MaxInt64), nil
434
return d * time.Duration(t), nil
443
// encodeGrpcMessage is used to encode status code in header field
444
// "grpc-message". It does percent encoding and also replaces invalid utf-8
445
// characters with Unicode replacement character.
447
// It checks to see if each individual byte in msg is an allowable byte, and
448
// then either percent encoding or passing it through. When percent encoding,
449
// the byte is converted into hexadecimal notation with a '%' prepended.
450
func encodeGrpcMessage(msg string) string {
455
for i := 0; i < lenMsg; i++ {
457
if !(c >= spaceByte && c <= tildeByte && c != percentByte) {
458
return encodeGrpcMessageUnchecked(msg)
464
func encodeGrpcMessageUnchecked(msg string) string {
467
r, size := utf8.DecodeRuneInString(msg)
468
for _, b := range []byte(string(r)) {
470
// If size > 1, r is not ascii. Always do percent encoding.
471
buf.WriteString(fmt.Sprintf("%%%02X", b))
475
// The for loop is necessary even if size == 1. r could be
478
// fmt.Sprintf("%%%02X", utf8.RuneError) gives "%FFFD".
479
if b >= spaceByte && b <= tildeByte && b != percentByte {
482
buf.WriteString(fmt.Sprintf("%%%02X", b))
490
// decodeGrpcMessage decodes the msg encoded by encodeGrpcMessage.
491
func decodeGrpcMessage(msg string) string {
496
for i := 0; i < lenMsg; i++ {
497
if msg[i] == percentByte && i+2 < lenMsg {
498
return decodeGrpcMessageUnchecked(msg)
504
func decodeGrpcMessageUnchecked(msg string) string {
507
for i := 0; i < lenMsg; i++ {
509
if c == percentByte && i+2 < lenMsg {
510
parsed, err := strconv.ParseUint(msg[i+1:i+3], 16, 8)
514
buf.WriteByte(byte(parsed))
524
type bufWriter struct {
534
func newBufWriter(conn net.Conn, batchSize int) *bufWriter {
536
buf: make([]byte, batchSize*2),
537
batchSize: batchSize,
542
func (w *bufWriter) Write(b []byte) (n int, err error) {
546
if w.batchSize == 0 { // Buffer has been disabled.
547
return w.conn.Write(b)
550
nn := copy(w.buf[w.offset:], b)
554
if w.offset >= w.batchSize {
561
func (w *bufWriter) Flush() error {
568
if w.onFlush != nil {
571
_, w.err = w.conn.Write(w.buf[:w.offset])
581
func newFramer(conn net.Conn, writeBufferSize, readBufferSize int, maxHeaderListSize uint32) *framer {
582
if writeBufferSize < 0 {
585
var r io.Reader = conn
586
if readBufferSize > 0 {
587
r = bufio.NewReaderSize(r, readBufferSize)
589
w := newBufWriter(conn, writeBufferSize)
592
fr: http2.NewFramer(w, r),
594
f.fr.SetMaxReadFrameSize(http2MaxFrameLen)
595
// Opt-in to Frame reuse API on framer to reduce garbage.
596
// Frames aren't safe to read from after a subsequent call to ReadFrame.
597
f.fr.SetReuseFrames()
598
f.fr.MaxHeaderListSize = maxHeaderListSize
599
f.fr.ReadMetaHeaders = hpack.NewDecoder(http2InitHeaderTableSize, nil)
603
// parseDialTarget returns the network and address to pass to dialer.
604
func parseDialTarget(target string) (string, string) {
606
m1 := strings.Index(target, ":")
607
m2 := strings.Index(target, ":/")
608
// handle unix:addr which will fail with url.Parse
609
if m1 >= 0 && m2 < 0 {
610
if n := target[0:m1]; n == "unix" {
611
return n, target[m1+1:]
615
t, err := url.Parse(target)
621
if scheme == "unix" {