cubefs

Форк
0
629 строк · 17.2 Кб
1
/*
2
 *
3
 * Copyright 2014 gRPC authors.
4
 *
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
8
 *
9
 *     http://www.apache.org/licenses/LICENSE-2.0
10
 *
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.
16
 *
17
 */
18

19
package transport
20

21
import (
22
	"bufio"
23
	"bytes"
24
	"encoding/base64"
25
	"fmt"
26
	"io"
27
	"math"
28
	"net"
29
	"net/http"
30
	"net/url"
31
	"strconv"
32
	"strings"
33
	"time"
34
	"unicode/utf8"
35

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"
44
)
45

46
const (
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
55
	// for more details.
56

57
)
58

59
var (
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,
76
	}
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,
95
	}
96
	logger = grpclog.Component("transport")
97
)
98

99
type parsedHeaderData struct {
100
	encoding string
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.
107
	rawStatusCode *int
108
	rawStatusMsg  string
109
	httpStatus    *int
110
	// Server side only fields.
111
	timeoutSet bool
112
	timeout    time.Duration
113
	method     string
114
	// key-value metadata map from the peer.
115
	mdata          map[string][]string
116
	statsTags      []byte
117
	statsTrace     []byte
118
	contentSubtype string
119

120
	// isGRPC field indicates whether the peer is speaking gRPC (otherwise HTTP).
121
	//
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.
126
	//
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.
129
	isGRPC         bool
130
	grpcErr        error
131
	httpErr        error
132
	contentTypeErr string
133
}
134

135
// decodeState configures decoding criteria and records the decoded data.
136
type decodeState struct {
137
	// whether decoding on server side or not
138
	serverSide bool
139

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
143
}
144

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] == ':' {
150
		return true
151
	}
152
	switch hdr {
153
	case "content-type",
154
		"user-agent",
155
		"grpc-message-type",
156
		"grpc-encoding",
157
		"grpc-message",
158
		"grpc-status",
159
		"grpc-timeout",
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.
164
		"te":
165
		return true
166
	default:
167
		return false
168
	}
169
}
170

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 {
174
	switch hdr {
175
	case ":authority", "user-agent":
176
		return true
177
	default:
178
		return false
179
	}
180
}
181

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)
186
	}
187
	return d.data.statusGen
188
}
189

190
const binHdrSuffix = "-bin"
191

192
func encodeBinHeader(v []byte) string {
193
	return base64.RawStdEncoding.EncodeToString(v)
194
}
195

196
func decodeBinHeader(v string) ([]byte, error) {
197
	if len(v)%4 == 0 {
198
		// Input was padded, or padding was not necessary.
199
		return base64.StdEncoding.DecodeString(v)
200
	}
201
	return base64.RawStdEncoding.DecodeString(v)
202
}
203

204
func encodeMetadataHeader(k, v string) string {
205
	if strings.HasSuffix(k, binHdrSuffix) {
206
		return encodeBinHeader(([]byte)(v))
207
	}
208
	return v
209
}
210

211
func decodeMetadataHeader(k, v string) (string, error) {
212
	if strings.HasSuffix(k, binHdrSuffix) {
213
		b, err := decodeBinHeader(v)
214
		return string(b), err
215
	}
216
	return v, nil
217
}
218

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.
222
	if frame.Truncated {
223
		return http2.ErrCodeFrameSize, status.Error(codes.Internal, "peer header list size exceeded limit")
224
	}
225

226
	for _, hf := range frame.Fields {
227
		d.processHeaderField(hf)
228
	}
229

230
	if d.data.isGRPC {
231
		if d.data.grpcErr != nil {
232
			return http2.ErrCodeProtocol, d.data.grpcErr
233
		}
234
		if d.serverSide {
235
			return http2.ErrCodeNo, nil
236
		}
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
246
		}
247
		return http2.ErrCodeNo, nil
248
	}
249

250
	// HTTP fallback mode
251
	if d.data.httpErr != nil {
252
		return http2.ErrCodeProtocol, d.data.httpErr
253
	}
254

255
	var (
256
		code = codes.Internal // when header does not include HTTP status, return INTERNAL
257
		ok   bool
258
	)
259

260
	if d.data.httpStatus != nil {
261
		code, ok = HTTPStatusConvTab[*(d.data.httpStatus)]
262
		if !ok {
263
			code = codes.Unknown
264
		}
265
	}
266

267
	return http2.ErrCodeProtocol, status.Error(code, d.constructHTTPErrMsg())
268
}
269

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 {
273
	var errMsgs []string
274

275
	if d.data.httpStatus == nil {
276
		errMsgs = append(errMsgs, "malformed header: missing HTTP status")
277
	} else {
278
		errMsgs = append(errMsgs, fmt.Sprintf("%s: HTTP status code %d", http.StatusText(*(d.data.httpStatus)), *d.data.httpStatus))
279
	}
280

281
	if d.data.contentTypeErr == "" {
282
		errMsgs = append(errMsgs, "transport: missing content-type field")
283
	} else {
284
		errMsgs = append(errMsgs, d.data.contentTypeErr)
285
	}
286

287
	return strings.Join(errMsgs, "; ")
288
}
289

290
func (d *decodeState) addMetadata(k, v string) {
291
	if d.data.mdata == nil {
292
		d.data.mdata = make(map[string][]string)
293
	}
294
	d.data.mdata[k] = append(d.data.mdata[k], v)
295
}
296

297
func (d *decodeState) processHeaderField(f hpack.HeaderField) {
298
	switch f.Name {
299
	case "content-type":
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)
303
			return
304
		}
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"}
309
		// in the metadata?
310
		d.addMetadata(f.Name, f.Value)
311
		d.data.isGRPC = true
312
	case "grpc-encoding":
313
		d.data.encoding = f.Value
314
	case "grpc-status":
315
		code, err := strconv.Atoi(f.Value)
316
		if err != nil {
317
			d.data.grpcErr = status.Errorf(codes.Internal, "transport: malformed grpc-status: %v", err)
318
			return
319
		}
320
		d.data.rawStatusCode = &code
321
	case "grpc-message":
322
		d.data.rawStatusMsg = decodeGrpcMessage(f.Value)
323
	case "grpc-status-details-bin":
324
		v, err := decodeBinHeader(f.Value)
325
		if err != nil {
326
			d.data.grpcErr = status.Errorf(codes.Internal, "transport: malformed grpc-status-details-bin: %v", err)
327
			return
328
		}
329
		s := &spb.Status{}
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)
332
			return
333
		}
334
		d.data.statusGen = status.FromProto(s)
335
	case "grpc-timeout":
336
		d.data.timeoutSet = true
337
		var err error
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)
340
		}
341
	case ":path":
342
		d.data.method = f.Value
343
	case ":status":
344
		code, err := strconv.Atoi(f.Value)
345
		if err != nil {
346
			d.data.httpErr = status.Errorf(codes.Internal, "transport: malformed http-status: %v", err)
347
			return
348
		}
349
		d.data.httpStatus = &code
350
	case "grpc-tags-bin":
351
		v, err := decodeBinHeader(f.Value)
352
		if err != nil {
353
			d.data.grpcErr = status.Errorf(codes.Internal, "transport: malformed grpc-tags-bin: %v", err)
354
			return
355
		}
356
		d.data.statsTags = v
357
		d.addMetadata(f.Name, string(v))
358
	case "grpc-trace-bin":
359
		v, err := decodeBinHeader(f.Value)
360
		if err != nil {
361
			d.data.grpcErr = status.Errorf(codes.Internal, "transport: malformed grpc-trace-bin: %v", err)
362
			return
363
		}
364
		d.data.statsTrace = v
365
		d.addMetadata(f.Name, string(v))
366
	default:
367
		if isReservedHeader(f.Name) && !isWhitelistedHeader(f.Name) {
368
			break
369
		}
370
		v, err := decodeMetadataHeader(f.Name, f.Value)
371
		if err != nil {
372
			if logger.V(logLevel) {
373
				logger.Errorf("Failed to decode metadata header (%q, %q): %v", f.Name, f.Value, err)
374
			}
375
			return
376
		}
377
		d.addMetadata(f.Name, v)
378
	}
379
}
380

381
type timeoutUnit uint8
382

383
const (
384
	hour        timeoutUnit = 'H'
385
	minute      timeoutUnit = 'M'
386
	second      timeoutUnit = 'S'
387
	millisecond timeoutUnit = 'm'
388
	microsecond timeoutUnit = 'u'
389
	nanosecond  timeoutUnit = 'n'
390
)
391

392
func timeoutUnitToDuration(u timeoutUnit) (d time.Duration, ok bool) {
393
	switch u {
394
	case hour:
395
		return time.Hour, true
396
	case minute:
397
		return time.Minute, true
398
	case second:
399
		return time.Second, true
400
	case millisecond:
401
		return time.Millisecond, true
402
	case microsecond:
403
		return time.Microsecond, true
404
	case nanosecond:
405
		return time.Nanosecond, true
406
	default:
407
	}
408
	return
409
}
410

411
func decodeTimeout(s string) (time.Duration, error) {
412
	size := len(s)
413
	if size < 2 {
414
		return 0, fmt.Errorf("transport: timeout string is too short: %q", s)
415
	}
416
	if size > 9 {
417
		// Spec allows for 8 digits plus the unit.
418
		return 0, fmt.Errorf("transport: timeout string is too long: %q", s)
419
	}
420
	unit := timeoutUnit(s[size-1])
421
	d, ok := timeoutUnitToDuration(unit)
422
	if !ok {
423
		return 0, fmt.Errorf("transport: timeout unit is not recognized: %q", s)
424
	}
425
	t, err := strconv.ParseInt(s[:size-1], 10, 64)
426
	if err != nil {
427
		return 0, err
428
	}
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
433
	}
434
	return d * time.Duration(t), nil
435
}
436

437
const (
438
	spaceByte   = ' '
439
	tildeByte   = '~'
440
	percentByte = '%'
441
)
442

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.
446
//
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 {
451
	if msg == "" {
452
		return ""
453
	}
454
	lenMsg := len(msg)
455
	for i := 0; i < lenMsg; i++ {
456
		c := msg[i]
457
		if !(c >= spaceByte && c <= tildeByte && c != percentByte) {
458
			return encodeGrpcMessageUnchecked(msg)
459
		}
460
	}
461
	return msg
462
}
463

464
func encodeGrpcMessageUnchecked(msg string) string {
465
	var buf bytes.Buffer
466
	for len(msg) > 0 {
467
		r, size := utf8.DecodeRuneInString(msg)
468
		for _, b := range []byte(string(r)) {
469
			if size > 1 {
470
				// If size > 1, r is not ascii. Always do percent encoding.
471
				buf.WriteString(fmt.Sprintf("%%%02X", b))
472
				continue
473
			}
474

475
			// The for loop is necessary even if size == 1. r could be
476
			// utf8.RuneError.
477
			//
478
			// fmt.Sprintf("%%%02X", utf8.RuneError) gives "%FFFD".
479
			if b >= spaceByte && b <= tildeByte && b != percentByte {
480
				buf.WriteByte(b)
481
			} else {
482
				buf.WriteString(fmt.Sprintf("%%%02X", b))
483
			}
484
		}
485
		msg = msg[size:]
486
	}
487
	return buf.String()
488
}
489

490
// decodeGrpcMessage decodes the msg encoded by encodeGrpcMessage.
491
func decodeGrpcMessage(msg string) string {
492
	if msg == "" {
493
		return ""
494
	}
495
	lenMsg := len(msg)
496
	for i := 0; i < lenMsg; i++ {
497
		if msg[i] == percentByte && i+2 < lenMsg {
498
			return decodeGrpcMessageUnchecked(msg)
499
		}
500
	}
501
	return msg
502
}
503

504
func decodeGrpcMessageUnchecked(msg string) string {
505
	var buf bytes.Buffer
506
	lenMsg := len(msg)
507
	for i := 0; i < lenMsg; i++ {
508
		c := msg[i]
509
		if c == percentByte && i+2 < lenMsg {
510
			parsed, err := strconv.ParseUint(msg[i+1:i+3], 16, 8)
511
			if err != nil {
512
				buf.WriteByte(c)
513
			} else {
514
				buf.WriteByte(byte(parsed))
515
				i += 2
516
			}
517
		} else {
518
			buf.WriteByte(c)
519
		}
520
	}
521
	return buf.String()
522
}
523

524
type bufWriter struct {
525
	buf       []byte
526
	offset    int
527
	batchSize int
528
	conn      net.Conn
529
	err       error
530

531
	onFlush func()
532
}
533

534
func newBufWriter(conn net.Conn, batchSize int) *bufWriter {
535
	return &bufWriter{
536
		buf:       make([]byte, batchSize*2),
537
		batchSize: batchSize,
538
		conn:      conn,
539
	}
540
}
541

542
func (w *bufWriter) Write(b []byte) (n int, err error) {
543
	if w.err != nil {
544
		return 0, w.err
545
	}
546
	if w.batchSize == 0 { // Buffer has been disabled.
547
		return w.conn.Write(b)
548
	}
549
	for len(b) > 0 {
550
		nn := copy(w.buf[w.offset:], b)
551
		b = b[nn:]
552
		w.offset += nn
553
		n += nn
554
		if w.offset >= w.batchSize {
555
			err = w.Flush()
556
		}
557
	}
558
	return n, err
559
}
560

561
func (w *bufWriter) Flush() error {
562
	if w.err != nil {
563
		return w.err
564
	}
565
	if w.offset == 0 {
566
		return nil
567
	}
568
	if w.onFlush != nil {
569
		w.onFlush()
570
	}
571
	_, w.err = w.conn.Write(w.buf[:w.offset])
572
	w.offset = 0
573
	return w.err
574
}
575

576
type framer struct {
577
	writer *bufWriter
578
	fr     *http2.Framer
579
}
580

581
func newFramer(conn net.Conn, writeBufferSize, readBufferSize int, maxHeaderListSize uint32) *framer {
582
	if writeBufferSize < 0 {
583
		writeBufferSize = 0
584
	}
585
	var r io.Reader = conn
586
	if readBufferSize > 0 {
587
		r = bufio.NewReaderSize(r, readBufferSize)
588
	}
589
	w := newBufWriter(conn, writeBufferSize)
590
	f := &framer{
591
		writer: w,
592
		fr:     http2.NewFramer(w, r),
593
	}
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)
600
	return f
601
}
602

603
// parseDialTarget returns the network and address to pass to dialer.
604
func parseDialTarget(target string) (string, string) {
605
	net := "tcp"
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:]
612
		}
613
	}
614
	if m2 >= 0 {
615
		t, err := url.Parse(target)
616
		if err != nil {
617
			return net, target
618
		}
619
		scheme := t.Scheme
620
		addr := t.Path
621
		if scheme == "unix" {
622
			if addr == "" {
623
				addr = t.Host
624
			}
625
			return scheme, addr
626
		}
627
	}
628
	return net, target
629
}
630

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.