blob: 2521a7d7a408fe53662797c3bb8457ec09e0ac5e [file] [log] [blame]
khenaidoo5fc5cea2021-08-11 17:39:16 -04001/*
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
19package transport
20
21import (
22 "context"
23 "fmt"
24 "io"
25 "math"
26 "net"
27 "net/http"
khenaidoo5cb0d402021-12-08 14:09:16 -050028 "path/filepath"
khenaidoo5fc5cea2021-08-11 17:39:16 -040029 "strconv"
30 "strings"
31 "sync"
32 "sync/atomic"
33 "time"
34
35 "golang.org/x/net/http2"
36 "golang.org/x/net/http2/hpack"
37 "google.golang.org/grpc/codes"
38 "google.golang.org/grpc/credentials"
39 "google.golang.org/grpc/internal/channelz"
40 icredentials "google.golang.org/grpc/internal/credentials"
41 "google.golang.org/grpc/internal/grpcutil"
42 imetadata "google.golang.org/grpc/internal/metadata"
43 "google.golang.org/grpc/internal/syscall"
44 "google.golang.org/grpc/internal/transport/networktype"
45 "google.golang.org/grpc/keepalive"
46 "google.golang.org/grpc/metadata"
47 "google.golang.org/grpc/peer"
48 "google.golang.org/grpc/resolver"
49 "google.golang.org/grpc/stats"
50 "google.golang.org/grpc/status"
51)
52
53// clientConnectionCounter counts the number of connections a client has
54// initiated (equal to the number of http2Clients created). Must be accessed
55// atomically.
56var clientConnectionCounter uint64
57
58// http2Client implements the ClientTransport interface with HTTP2.
59type http2Client struct {
60 lastRead int64 // Keep this field 64-bit aligned. Accessed atomically.
61 ctx context.Context
62 cancel context.CancelFunc
63 ctxDone <-chan struct{} // Cache the ctx.Done() chan.
64 userAgent string
65 md metadata.MD
66 conn net.Conn // underlying communication channel
67 loopy *loopyWriter
68 remoteAddr net.Addr
69 localAddr net.Addr
70 authInfo credentials.AuthInfo // auth info about the connection
71
72 readerDone chan struct{} // sync point to enable testing.
73 writerDone chan struct{} // sync point to enable testing.
74 // goAway is closed to notify the upper layer (i.e., addrConn.transportMonitor)
75 // that the server sent GoAway on this transport.
76 goAway chan struct{}
77
78 framer *framer
79 // controlBuf delivers all the control related tasks (e.g., window
80 // updates, reset streams, and various settings) to the controller.
81 controlBuf *controlBuffer
82 fc *trInFlow
83 // The scheme used: https if TLS is on, http otherwise.
84 scheme string
85
86 isSecure bool
87
88 perRPCCreds []credentials.PerRPCCredentials
89
90 kp keepalive.ClientParameters
91 keepaliveEnabled bool
92
93 statsHandler stats.Handler
94
95 initialWindowSize int32
96
97 // configured by peer through SETTINGS_MAX_HEADER_LIST_SIZE
98 maxSendHeaderListSize *uint32
99
100 bdpEst *bdpEstimator
101 // onPrefaceReceipt is a callback that client transport calls upon
102 // receiving server preface to signal that a succefull HTTP2
103 // connection was established.
104 onPrefaceReceipt func()
105
106 maxConcurrentStreams uint32
107 streamQuota int64
108 streamsQuotaAvailable chan struct{}
109 waitingStreams uint32
110 nextID uint32
111
112 mu sync.Mutex // guard the following variables
113 state transportState
114 activeStreams map[uint32]*Stream
115 // prevGoAway ID records the Last-Stream-ID in the previous GOAway frame.
116 prevGoAwayID uint32
117 // goAwayReason records the http2.ErrCode and debug data received with the
118 // GoAway frame.
119 goAwayReason GoAwayReason
120 // goAwayDebugMessage contains a detailed human readable string about a
121 // GoAway frame, useful for error messages.
122 goAwayDebugMessage string
123 // A condition variable used to signal when the keepalive goroutine should
124 // go dormant. The condition for dormancy is based on the number of active
125 // streams and the `PermitWithoutStream` keepalive client parameter. And
126 // since the number of active streams is guarded by the above mutex, we use
127 // the same for this condition variable as well.
128 kpDormancyCond *sync.Cond
129 // A boolean to track whether the keepalive goroutine is dormant or not.
130 // This is checked before attempting to signal the above condition
131 // variable.
132 kpDormant bool
133
134 // Fields below are for channelz metric collection.
135 channelzID int64 // channelz unique identification number
136 czData *channelzData
137
138 onGoAway func(GoAwayReason)
139 onClose func()
140
141 bufferPool *bufferPool
142
143 connectionID uint64
144}
145
146func dial(ctx context.Context, fn func(context.Context, string) (net.Conn, error), addr resolver.Address, useProxy bool, grpcUA string) (net.Conn, error) {
147 address := addr.Addr
148 networkType, ok := networktype.Get(addr)
149 if fn != nil {
khenaidoo5cb0d402021-12-08 14:09:16 -0500150 // Special handling for unix scheme with custom dialer. Back in the day,
151 // we did not have a unix resolver and therefore targets with a unix
152 // scheme would end up using the passthrough resolver. So, user's used a
153 // custom dialer in this case and expected the original dial target to
154 // be passed to the custom dialer. Now, we have a unix resolver. But if
155 // a custom dialer is specified, we want to retain the old behavior in
156 // terms of the address being passed to the custom dialer.
khenaidoo5fc5cea2021-08-11 17:39:16 -0400157 if networkType == "unix" && !strings.HasPrefix(address, "\x00") {
khenaidoo5cb0d402021-12-08 14:09:16 -0500158 // Supported unix targets are either "unix://absolute-path" or
159 // "unix:relative-path".
160 if filepath.IsAbs(address) {
161 return fn(ctx, "unix://"+address)
162 }
163 return fn(ctx, "unix:"+address)
khenaidoo5fc5cea2021-08-11 17:39:16 -0400164 }
165 return fn(ctx, address)
166 }
167 if !ok {
168 networkType, address = parseDialTarget(address)
169 }
170 if networkType == "tcp" && useProxy {
171 return proxyDial(ctx, address, grpcUA)
172 }
173 return (&net.Dialer{}).DialContext(ctx, networkType, address)
174}
175
176func isTemporary(err error) bool {
177 switch err := err.(type) {
178 case interface {
179 Temporary() bool
180 }:
181 return err.Temporary()
182 case interface {
183 Timeout() bool
184 }:
185 // Timeouts may be resolved upon retry, and are thus treated as
186 // temporary.
187 return err.Timeout()
188 }
189 return true
190}
191
192// newHTTP2Client constructs a connected ClientTransport to addr based on HTTP2
193// and starts to receive messages on it. Non-nil error returns if construction
194// fails.
195func newHTTP2Client(connectCtx, ctx context.Context, addr resolver.Address, opts ConnectOptions, onPrefaceReceipt func(), onGoAway func(GoAwayReason), onClose func()) (_ *http2Client, err error) {
196 scheme := "http"
197 ctx, cancel := context.WithCancel(ctx)
198 defer func() {
199 if err != nil {
200 cancel()
201 }
202 }()
203
204 conn, err := dial(connectCtx, opts.Dialer, addr, opts.UseProxy, opts.UserAgent)
205 if err != nil {
206 if opts.FailOnNonTempDialError {
207 return nil, connectionErrorf(isTemporary(err), err, "transport: error while dialing: %v", err)
208 }
209 return nil, connectionErrorf(true, err, "transport: Error while dialing %v", err)
210 }
211 // Any further errors will close the underlying connection
212 defer func(conn net.Conn) {
213 if err != nil {
214 conn.Close()
215 }
216 }(conn)
217 kp := opts.KeepaliveParams
218 // Validate keepalive parameters.
219 if kp.Time == 0 {
220 kp.Time = defaultClientKeepaliveTime
221 }
222 if kp.Timeout == 0 {
223 kp.Timeout = defaultClientKeepaliveTimeout
224 }
225 keepaliveEnabled := false
226 if kp.Time != infinity {
227 if err = syscall.SetTCPUserTimeout(conn, kp.Timeout); err != nil {
228 return nil, connectionErrorf(false, err, "transport: failed to set TCP_USER_TIMEOUT: %v", err)
229 }
230 keepaliveEnabled = true
231 }
232 var (
233 isSecure bool
234 authInfo credentials.AuthInfo
235 )
236 transportCreds := opts.TransportCredentials
237 perRPCCreds := opts.PerRPCCredentials
238
239 if b := opts.CredsBundle; b != nil {
240 if t := b.TransportCredentials(); t != nil {
241 transportCreds = t
242 }
243 if t := b.PerRPCCredentials(); t != nil {
244 perRPCCreds = append(perRPCCreds, t)
245 }
246 }
247 if transportCreds != nil {
248 // gRPC, resolver, balancer etc. can specify arbitrary data in the
249 // Attributes field of resolver.Address, which is shoved into connectCtx
250 // and passed to the credential handshaker. This makes it possible for
251 // address specific arbitrary data to reach the credential handshaker.
252 connectCtx = icredentials.NewClientHandshakeInfoContext(connectCtx, credentials.ClientHandshakeInfo{Attributes: addr.Attributes})
253 rawConn := conn
254 // Pull the deadline from the connectCtx, which will be used for
255 // timeouts in the authentication protocol handshake. Can ignore the
256 // boolean as the deadline will return the zero value, which will make
257 // the conn not timeout on I/O operations.
258 deadline, _ := connectCtx.Deadline()
259 rawConn.SetDeadline(deadline)
260 conn, authInfo, err = transportCreds.ClientHandshake(connectCtx, addr.ServerName, rawConn)
261 rawConn.SetDeadline(time.Time{})
262 if err != nil {
263 return nil, connectionErrorf(isTemporary(err), err, "transport: authentication handshake failed: %v", err)
264 }
265 for _, cd := range perRPCCreds {
266 if cd.RequireTransportSecurity() {
267 if ci, ok := authInfo.(interface {
268 GetCommonAuthInfo() credentials.CommonAuthInfo
269 }); ok {
270 secLevel := ci.GetCommonAuthInfo().SecurityLevel
271 if secLevel != credentials.InvalidSecurityLevel && secLevel < credentials.PrivacyAndIntegrity {
272 return nil, connectionErrorf(true, nil, "transport: cannot send secure credentials on an insecure connection")
273 }
274 }
275 }
276 }
277 isSecure = true
278 if transportCreds.Info().SecurityProtocol == "tls" {
279 scheme = "https"
280 }
281 }
282 dynamicWindow := true
283 icwz := int32(initialWindowSize)
284 if opts.InitialConnWindowSize >= defaultWindowSize {
285 icwz = opts.InitialConnWindowSize
286 dynamicWindow = false
287 }
288 writeBufSize := opts.WriteBufferSize
289 readBufSize := opts.ReadBufferSize
290 maxHeaderListSize := defaultClientMaxHeaderListSize
291 if opts.MaxHeaderListSize != nil {
292 maxHeaderListSize = *opts.MaxHeaderListSize
293 }
294 t := &http2Client{
295 ctx: ctx,
296 ctxDone: ctx.Done(), // Cache Done chan.
297 cancel: cancel,
298 userAgent: opts.UserAgent,
299 conn: conn,
300 remoteAddr: conn.RemoteAddr(),
301 localAddr: conn.LocalAddr(),
302 authInfo: authInfo,
303 readerDone: make(chan struct{}),
304 writerDone: make(chan struct{}),
305 goAway: make(chan struct{}),
306 framer: newFramer(conn, writeBufSize, readBufSize, maxHeaderListSize),
307 fc: &trInFlow{limit: uint32(icwz)},
308 scheme: scheme,
309 activeStreams: make(map[uint32]*Stream),
310 isSecure: isSecure,
311 perRPCCreds: perRPCCreds,
312 kp: kp,
313 statsHandler: opts.StatsHandler,
314 initialWindowSize: initialWindowSize,
315 onPrefaceReceipt: onPrefaceReceipt,
316 nextID: 1,
317 maxConcurrentStreams: defaultMaxStreamsClient,
318 streamQuota: defaultMaxStreamsClient,
319 streamsQuotaAvailable: make(chan struct{}, 1),
320 czData: new(channelzData),
321 onGoAway: onGoAway,
322 onClose: onClose,
323 keepaliveEnabled: keepaliveEnabled,
324 bufferPool: newBufferPool(),
325 }
326
327 if md, ok := addr.Metadata.(*metadata.MD); ok {
328 t.md = *md
329 } else if md := imetadata.Get(addr); md != nil {
330 t.md = md
331 }
332 t.controlBuf = newControlBuffer(t.ctxDone)
333 if opts.InitialWindowSize >= defaultWindowSize {
334 t.initialWindowSize = opts.InitialWindowSize
335 dynamicWindow = false
336 }
337 if dynamicWindow {
338 t.bdpEst = &bdpEstimator{
339 bdp: initialWindowSize,
340 updateFlowControl: t.updateFlowControl,
341 }
342 }
343 if t.statsHandler != nil {
344 t.ctx = t.statsHandler.TagConn(t.ctx, &stats.ConnTagInfo{
345 RemoteAddr: t.remoteAddr,
346 LocalAddr: t.localAddr,
347 })
348 connBegin := &stats.ConnBegin{
349 Client: true,
350 }
351 t.statsHandler.HandleConn(t.ctx, connBegin)
352 }
353 if channelz.IsOn() {
354 t.channelzID = channelz.RegisterNormalSocket(t, opts.ChannelzParentID, fmt.Sprintf("%s -> %s", t.localAddr, t.remoteAddr))
355 }
356 if t.keepaliveEnabled {
357 t.kpDormancyCond = sync.NewCond(&t.mu)
358 go t.keepalive()
359 }
360 // Start the reader goroutine for incoming message. Each transport has
361 // a dedicated goroutine which reads HTTP2 frame from network. Then it
362 // dispatches the frame to the corresponding stream entity.
363 go t.reader()
364
365 // Send connection preface to server.
366 n, err := t.conn.Write(clientPreface)
367 if err != nil {
368 err = connectionErrorf(true, err, "transport: failed to write client preface: %v", err)
369 t.Close(err)
370 return nil, err
371 }
372 if n != len(clientPreface) {
373 err = connectionErrorf(true, nil, "transport: preface mismatch, wrote %d bytes; want %d", n, len(clientPreface))
374 t.Close(err)
375 return nil, err
376 }
377 var ss []http2.Setting
378
379 if t.initialWindowSize != defaultWindowSize {
380 ss = append(ss, http2.Setting{
381 ID: http2.SettingInitialWindowSize,
382 Val: uint32(t.initialWindowSize),
383 })
384 }
385 if opts.MaxHeaderListSize != nil {
386 ss = append(ss, http2.Setting{
387 ID: http2.SettingMaxHeaderListSize,
388 Val: *opts.MaxHeaderListSize,
389 })
390 }
391 err = t.framer.fr.WriteSettings(ss...)
392 if err != nil {
393 err = connectionErrorf(true, err, "transport: failed to write initial settings frame: %v", err)
394 t.Close(err)
395 return nil, err
396 }
397 // Adjust the connection flow control window if needed.
398 if delta := uint32(icwz - defaultWindowSize); delta > 0 {
399 if err := t.framer.fr.WriteWindowUpdate(0, delta); err != nil {
400 err = connectionErrorf(true, err, "transport: failed to write window update: %v", err)
401 t.Close(err)
402 return nil, err
403 }
404 }
405
406 t.connectionID = atomic.AddUint64(&clientConnectionCounter, 1)
407
408 if err := t.framer.writer.Flush(); err != nil {
409 return nil, err
410 }
411 go func() {
412 t.loopy = newLoopyWriter(clientSide, t.framer, t.controlBuf, t.bdpEst)
413 err := t.loopy.run()
414 if err != nil {
415 if logger.V(logLevel) {
416 logger.Errorf("transport: loopyWriter.run returning. Err: %v", err)
417 }
418 }
419 // Do not close the transport. Let reader goroutine handle it since
420 // there might be data in the buffers.
421 t.conn.Close()
422 t.controlBuf.finish()
423 close(t.writerDone)
424 }()
425 return t, nil
426}
427
428func (t *http2Client) newStream(ctx context.Context, callHdr *CallHdr) *Stream {
429 // TODO(zhaoq): Handle uint32 overflow of Stream.id.
430 s := &Stream{
431 ct: t,
432 done: make(chan struct{}),
433 method: callHdr.Method,
434 sendCompress: callHdr.SendCompress,
435 buf: newRecvBuffer(),
436 headerChan: make(chan struct{}),
437 contentSubtype: callHdr.ContentSubtype,
438 doneFunc: callHdr.DoneFunc,
439 }
440 s.wq = newWriteQuota(defaultWriteQuota, s.done)
441 s.requestRead = func(n int) {
442 t.adjustWindow(s, uint32(n))
443 }
444 // The client side stream context should have exactly the same life cycle with the user provided context.
445 // That means, s.ctx should be read-only. And s.ctx is done iff ctx is done.
446 // So we use the original context here instead of creating a copy.
447 s.ctx = ctx
448 s.trReader = &transportReader{
449 reader: &recvBufferReader{
450 ctx: s.ctx,
451 ctxDone: s.ctx.Done(),
452 recv: s.buf,
453 closeStream: func(err error) {
454 t.CloseStream(s, err)
455 },
456 freeBuffer: t.bufferPool.put,
457 },
458 windowHandler: func(n int) {
459 t.updateWindow(s, uint32(n))
460 },
461 }
462 return s
463}
464
465func (t *http2Client) getPeer() *peer.Peer {
466 return &peer.Peer{
467 Addr: t.remoteAddr,
468 AuthInfo: t.authInfo,
469 }
470}
471
472func (t *http2Client) createHeaderFields(ctx context.Context, callHdr *CallHdr) ([]hpack.HeaderField, error) {
473 aud := t.createAudience(callHdr)
474 ri := credentials.RequestInfo{
475 Method: callHdr.Method,
476 AuthInfo: t.authInfo,
477 }
478 ctxWithRequestInfo := icredentials.NewRequestInfoContext(ctx, ri)
479 authData, err := t.getTrAuthData(ctxWithRequestInfo, aud)
480 if err != nil {
481 return nil, err
482 }
483 callAuthData, err := t.getCallAuthData(ctxWithRequestInfo, aud, callHdr)
484 if err != nil {
485 return nil, err
486 }
487 // TODO(mmukhi): Benchmark if the performance gets better if count the metadata and other header fields
488 // first and create a slice of that exact size.
489 // Make the slice of certain predictable size to reduce allocations made by append.
490 hfLen := 7 // :method, :scheme, :path, :authority, content-type, user-agent, te
491 hfLen += len(authData) + len(callAuthData)
492 headerFields := make([]hpack.HeaderField, 0, hfLen)
493 headerFields = append(headerFields, hpack.HeaderField{Name: ":method", Value: "POST"})
494 headerFields = append(headerFields, hpack.HeaderField{Name: ":scheme", Value: t.scheme})
495 headerFields = append(headerFields, hpack.HeaderField{Name: ":path", Value: callHdr.Method})
496 headerFields = append(headerFields, hpack.HeaderField{Name: ":authority", Value: callHdr.Host})
497 headerFields = append(headerFields, hpack.HeaderField{Name: "content-type", Value: grpcutil.ContentType(callHdr.ContentSubtype)})
498 headerFields = append(headerFields, hpack.HeaderField{Name: "user-agent", Value: t.userAgent})
499 headerFields = append(headerFields, hpack.HeaderField{Name: "te", Value: "trailers"})
500 if callHdr.PreviousAttempts > 0 {
501 headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-previous-rpc-attempts", Value: strconv.Itoa(callHdr.PreviousAttempts)})
502 }
503
504 if callHdr.SendCompress != "" {
505 headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-encoding", Value: callHdr.SendCompress})
506 headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-accept-encoding", Value: callHdr.SendCompress})
507 }
508 if dl, ok := ctx.Deadline(); ok {
509 // Send out timeout regardless its value. The server can detect timeout context by itself.
510 // TODO(mmukhi): Perhaps this field should be updated when actually writing out to the wire.
511 timeout := time.Until(dl)
512 headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-timeout", Value: grpcutil.EncodeDuration(timeout)})
513 }
514 for k, v := range authData {
515 headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
516 }
517 for k, v := range callAuthData {
518 headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
519 }
520 if b := stats.OutgoingTags(ctx); b != nil {
521 headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-tags-bin", Value: encodeBinHeader(b)})
522 }
523 if b := stats.OutgoingTrace(ctx); b != nil {
524 headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-trace-bin", Value: encodeBinHeader(b)})
525 }
526
527 if md, added, ok := metadata.FromOutgoingContextRaw(ctx); ok {
528 var k string
529 for k, vv := range md {
530 // HTTP doesn't allow you to set pseudoheaders after non pseudoheaders were set.
531 if isReservedHeader(k) {
532 continue
533 }
534 for _, v := range vv {
535 headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
536 }
537 }
538 for _, vv := range added {
539 for i, v := range vv {
540 if i%2 == 0 {
541 k = strings.ToLower(v)
542 continue
543 }
544 // HTTP doesn't allow you to set pseudoheaders after non pseudoheaders were set.
545 if isReservedHeader(k) {
546 continue
547 }
548 headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
549 }
550 }
551 }
552 for k, vv := range t.md {
553 if isReservedHeader(k) {
554 continue
555 }
556 for _, v := range vv {
557 headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
558 }
559 }
560 return headerFields, nil
561}
562
563func (t *http2Client) createAudience(callHdr *CallHdr) string {
564 // Create an audience string only if needed.
565 if len(t.perRPCCreds) == 0 && callHdr.Creds == nil {
566 return ""
567 }
568 // Construct URI required to get auth request metadata.
569 // Omit port if it is the default one.
570 host := strings.TrimSuffix(callHdr.Host, ":443")
571 pos := strings.LastIndex(callHdr.Method, "/")
572 if pos == -1 {
573 pos = len(callHdr.Method)
574 }
575 return "https://" + host + callHdr.Method[:pos]
576}
577
578func (t *http2Client) getTrAuthData(ctx context.Context, audience string) (map[string]string, error) {
579 if len(t.perRPCCreds) == 0 {
580 return nil, nil
581 }
582 authData := map[string]string{}
583 for _, c := range t.perRPCCreds {
584 data, err := c.GetRequestMetadata(ctx, audience)
585 if err != nil {
586 if _, ok := status.FromError(err); ok {
587 return nil, err
588 }
589
590 return nil, status.Errorf(codes.Unauthenticated, "transport: %v", err)
591 }
592 for k, v := range data {
593 // Capital header names are illegal in HTTP/2.
594 k = strings.ToLower(k)
595 authData[k] = v
596 }
597 }
598 return authData, nil
599}
600
601func (t *http2Client) getCallAuthData(ctx context.Context, audience string, callHdr *CallHdr) (map[string]string, error) {
602 var callAuthData map[string]string
603 // Check if credentials.PerRPCCredentials were provided via call options.
604 // Note: if these credentials are provided both via dial options and call
605 // options, then both sets of credentials will be applied.
606 if callCreds := callHdr.Creds; callCreds != nil {
607 if callCreds.RequireTransportSecurity() {
608 ri, _ := credentials.RequestInfoFromContext(ctx)
609 if !t.isSecure || credentials.CheckSecurityLevel(ri.AuthInfo, credentials.PrivacyAndIntegrity) != nil {
610 return nil, status.Error(codes.Unauthenticated, "transport: cannot send secure credentials on an insecure connection")
611 }
612 }
613 data, err := callCreds.GetRequestMetadata(ctx, audience)
614 if err != nil {
615 return nil, status.Errorf(codes.Internal, "transport: %v", err)
616 }
617 callAuthData = make(map[string]string, len(data))
618 for k, v := range data {
619 // Capital header names are illegal in HTTP/2
620 k = strings.ToLower(k)
621 callAuthData[k] = v
622 }
623 }
624 return callAuthData, nil
625}
626
627// NewStreamError wraps an error and reports additional information. Typically
628// NewStream errors result in transparent retry, as they mean nothing went onto
629// the wire. However, there are two notable exceptions:
630//
631// 1. If the stream headers violate the max header list size allowed by the
632// server. In this case there is no reason to retry at all, as it is
633// assumed the RPC would continue to fail on subsequent attempts.
634// 2. If the credentials errored when requesting their headers. In this case,
635// it's possible a retry can fix the problem, but indefinitely transparently
636// retrying is not appropriate as it is likely the credentials, if they can
637// eventually succeed, would need I/O to do so.
638type NewStreamError struct {
639 Err error
640
641 DoNotRetry bool
642 DoNotTransparentRetry bool
643}
644
645func (e NewStreamError) Error() string {
646 return e.Err.Error()
647}
648
649// NewStream creates a stream and registers it into the transport as "active"
650// streams. All non-nil errors returned will be *NewStreamError.
651func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Stream, err error) {
652 ctx = peer.NewContext(ctx, t.getPeer())
653 headerFields, err := t.createHeaderFields(ctx, callHdr)
654 if err != nil {
655 return nil, &NewStreamError{Err: err, DoNotTransparentRetry: true}
656 }
657 s := t.newStream(ctx, callHdr)
658 cleanup := func(err error) {
659 if s.swapState(streamDone) == streamDone {
660 // If it was already done, return.
661 return
662 }
663 // The stream was unprocessed by the server.
664 atomic.StoreUint32(&s.unprocessed, 1)
665 s.write(recvMsg{err: err})
666 close(s.done)
667 // If headerChan isn't closed, then close it.
668 if atomic.CompareAndSwapUint32(&s.headerChanClosed, 0, 1) {
669 close(s.headerChan)
670 }
671 }
672 hdr := &headerFrame{
673 hf: headerFields,
674 endStream: false,
675 initStream: func(id uint32) error {
676 t.mu.Lock()
677 if state := t.state; state != reachable {
678 t.mu.Unlock()
679 // Do a quick cleanup.
680 err := error(errStreamDrain)
681 if state == closing {
682 err = ErrConnClosing
683 }
684 cleanup(err)
685 return err
686 }
687 t.activeStreams[id] = s
688 if channelz.IsOn() {
689 atomic.AddInt64(&t.czData.streamsStarted, 1)
690 atomic.StoreInt64(&t.czData.lastStreamCreatedTime, time.Now().UnixNano())
691 }
692 // If the keepalive goroutine has gone dormant, wake it up.
693 if t.kpDormant {
694 t.kpDormancyCond.Signal()
695 }
696 t.mu.Unlock()
697 return nil
698 },
699 onOrphaned: cleanup,
700 wq: s.wq,
701 }
702 firstTry := true
703 var ch chan struct{}
704 checkForStreamQuota := func(it interface{}) bool {
705 if t.streamQuota <= 0 { // Can go negative if server decreases it.
706 if firstTry {
707 t.waitingStreams++
708 }
709 ch = t.streamsQuotaAvailable
710 return false
711 }
712 if !firstTry {
713 t.waitingStreams--
714 }
715 t.streamQuota--
716 h := it.(*headerFrame)
717 h.streamID = t.nextID
718 t.nextID += 2
719 s.id = h.streamID
720 s.fc = &inFlow{limit: uint32(t.initialWindowSize)}
721 if t.streamQuota > 0 && t.waitingStreams > 0 {
722 select {
723 case t.streamsQuotaAvailable <- struct{}{}:
724 default:
725 }
726 }
727 return true
728 }
729 var hdrListSizeErr error
730 checkForHeaderListSize := func(it interface{}) bool {
731 if t.maxSendHeaderListSize == nil {
732 return true
733 }
734 hdrFrame := it.(*headerFrame)
735 var sz int64
736 for _, f := range hdrFrame.hf {
737 if sz += int64(f.Size()); sz > int64(*t.maxSendHeaderListSize) {
738 hdrListSizeErr = status.Errorf(codes.Internal, "header list size to send violates the maximum size (%d bytes) set by server", *t.maxSendHeaderListSize)
739 return false
740 }
741 }
742 return true
743 }
744 for {
745 success, err := t.controlBuf.executeAndPut(func(it interface{}) bool {
746 if !checkForStreamQuota(it) {
747 return false
748 }
749 if !checkForHeaderListSize(it) {
750 return false
751 }
752 return true
753 }, hdr)
754 if err != nil {
755 return nil, &NewStreamError{Err: err}
756 }
757 if success {
758 break
759 }
760 if hdrListSizeErr != nil {
761 return nil, &NewStreamError{Err: hdrListSizeErr, DoNotRetry: true}
762 }
763 firstTry = false
764 select {
765 case <-ch:
766 case <-ctx.Done():
767 return nil, &NewStreamError{Err: ContextErr(ctx.Err())}
768 case <-t.goAway:
769 return nil, &NewStreamError{Err: errStreamDrain}
770 case <-t.ctx.Done():
771 return nil, &NewStreamError{Err: ErrConnClosing}
772 }
773 }
774 if t.statsHandler != nil {
775 header, ok := metadata.FromOutgoingContext(ctx)
776 if ok {
777 header.Set("user-agent", t.userAgent)
778 } else {
779 header = metadata.Pairs("user-agent", t.userAgent)
780 }
781 // Note: The header fields are compressed with hpack after this call returns.
782 // No WireLength field is set here.
783 outHeader := &stats.OutHeader{
784 Client: true,
785 FullMethod: callHdr.Method,
786 RemoteAddr: t.remoteAddr,
787 LocalAddr: t.localAddr,
788 Compression: callHdr.SendCompress,
789 Header: header,
790 }
791 t.statsHandler.HandleRPC(s.ctx, outHeader)
792 }
793 return s, nil
794}
795
796// CloseStream clears the footprint of a stream when the stream is not needed any more.
797// This must not be executed in reader's goroutine.
798func (t *http2Client) CloseStream(s *Stream, err error) {
799 var (
800 rst bool
801 rstCode http2.ErrCode
802 )
803 if err != nil {
804 rst = true
805 rstCode = http2.ErrCodeCancel
806 }
807 t.closeStream(s, err, rst, rstCode, status.Convert(err), nil, false)
808}
809
810func (t *http2Client) closeStream(s *Stream, err error, rst bool, rstCode http2.ErrCode, st *status.Status, mdata map[string][]string, eosReceived bool) {
811 // Set stream status to done.
812 if s.swapState(streamDone) == streamDone {
813 // If it was already done, return. If multiple closeStream calls
814 // happen simultaneously, wait for the first to finish.
815 <-s.done
816 return
817 }
818 // status and trailers can be updated here without any synchronization because the stream goroutine will
819 // only read it after it sees an io.EOF error from read or write and we'll write those errors
820 // only after updating this.
821 s.status = st
822 if len(mdata) > 0 {
823 s.trailer = mdata
824 }
825 if err != nil {
826 // This will unblock reads eventually.
827 s.write(recvMsg{err: err})
828 }
829 // If headerChan isn't closed, then close it.
830 if atomic.CompareAndSwapUint32(&s.headerChanClosed, 0, 1) {
831 s.noHeaders = true
832 close(s.headerChan)
833 }
834 cleanup := &cleanupStream{
835 streamID: s.id,
836 onWrite: func() {
837 t.mu.Lock()
838 if t.activeStreams != nil {
839 delete(t.activeStreams, s.id)
840 }
841 t.mu.Unlock()
842 if channelz.IsOn() {
843 if eosReceived {
844 atomic.AddInt64(&t.czData.streamsSucceeded, 1)
845 } else {
846 atomic.AddInt64(&t.czData.streamsFailed, 1)
847 }
848 }
849 },
850 rst: rst,
851 rstCode: rstCode,
852 }
853 addBackStreamQuota := func(interface{}) bool {
854 t.streamQuota++
855 if t.streamQuota > 0 && t.waitingStreams > 0 {
856 select {
857 case t.streamsQuotaAvailable <- struct{}{}:
858 default:
859 }
860 }
861 return true
862 }
863 t.controlBuf.executeAndPut(addBackStreamQuota, cleanup)
864 // This will unblock write.
865 close(s.done)
866 if s.doneFunc != nil {
867 s.doneFunc()
868 }
869}
870
871// Close kicks off the shutdown process of the transport. This should be called
872// only once on a transport. Once it is called, the transport should not be
873// accessed any more.
874//
875// This method blocks until the addrConn that initiated this transport is
876// re-connected. This happens because t.onClose() begins reconnect logic at the
877// addrConn level and blocks until the addrConn is successfully connected.
878func (t *http2Client) Close(err error) {
879 t.mu.Lock()
880 // Make sure we only Close once.
881 if t.state == closing {
882 t.mu.Unlock()
883 return
884 }
885 // Call t.onClose before setting the state to closing to prevent the client
886 // from attempting to create new streams ASAP.
887 t.onClose()
888 t.state = closing
889 streams := t.activeStreams
890 t.activeStreams = nil
891 if t.kpDormant {
892 // If the keepalive goroutine is blocked on this condition variable, we
893 // should unblock it so that the goroutine eventually exits.
894 t.kpDormancyCond.Signal()
895 }
896 t.mu.Unlock()
897 t.controlBuf.finish()
898 t.cancel()
899 t.conn.Close()
900 if channelz.IsOn() {
901 channelz.RemoveEntry(t.channelzID)
902 }
903 // Append info about previous goaways if there were any, since this may be important
904 // for understanding the root cause for this connection to be closed.
905 _, goAwayDebugMessage := t.GetGoAwayReason()
906
907 var st *status.Status
908 if len(goAwayDebugMessage) > 0 {
909 st = status.Newf(codes.Unavailable, "closing transport due to: %v, received prior goaway: %v", err, goAwayDebugMessage)
910 err = st.Err()
911 } else {
912 st = status.New(codes.Unavailable, err.Error())
913 }
914
915 // Notify all active streams.
916 for _, s := range streams {
917 t.closeStream(s, err, false, http2.ErrCodeNo, st, nil, false)
918 }
919 if t.statsHandler != nil {
920 connEnd := &stats.ConnEnd{
921 Client: true,
922 }
923 t.statsHandler.HandleConn(t.ctx, connEnd)
924 }
925}
926
927// GracefulClose sets the state to draining, which prevents new streams from
928// being created and causes the transport to be closed when the last active
929// stream is closed. If there are no active streams, the transport is closed
930// immediately. This does nothing if the transport is already draining or
931// closing.
932func (t *http2Client) GracefulClose() {
933 t.mu.Lock()
934 // Make sure we move to draining only from active.
935 if t.state == draining || t.state == closing {
936 t.mu.Unlock()
937 return
938 }
939 t.state = draining
940 active := len(t.activeStreams)
941 t.mu.Unlock()
942 if active == 0 {
943 t.Close(ErrConnClosing)
944 return
945 }
946 t.controlBuf.put(&incomingGoAway{})
947}
948
949// Write formats the data into HTTP2 data frame(s) and sends it out. The caller
950// should proceed only if Write returns nil.
951func (t *http2Client) Write(s *Stream, hdr []byte, data []byte, opts *Options) error {
952 if opts.Last {
953 // If it's the last message, update stream state.
954 if !s.compareAndSwapState(streamActive, streamWriteDone) {
955 return errStreamDone
956 }
957 } else if s.getState() != streamActive {
958 return errStreamDone
959 }
960 df := &dataFrame{
961 streamID: s.id,
962 endStream: opts.Last,
963 h: hdr,
964 d: data,
965 }
966 if hdr != nil || data != nil { // If it's not an empty data frame, check quota.
967 if err := s.wq.get(int32(len(hdr) + len(data))); err != nil {
968 return err
969 }
970 }
971 return t.controlBuf.put(df)
972}
973
974func (t *http2Client) getStream(f http2.Frame) *Stream {
975 t.mu.Lock()
976 s := t.activeStreams[f.Header().StreamID]
977 t.mu.Unlock()
978 return s
979}
980
981// adjustWindow sends out extra window update over the initial window size
982// of stream if the application is requesting data larger in size than
983// the window.
984func (t *http2Client) adjustWindow(s *Stream, n uint32) {
985 if w := s.fc.maybeAdjust(n); w > 0 {
986 t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, increment: w})
987 }
988}
989
990// updateWindow adjusts the inbound quota for the stream.
991// Window updates will be sent out when the cumulative quota
992// exceeds the corresponding threshold.
993func (t *http2Client) updateWindow(s *Stream, n uint32) {
994 if w := s.fc.onRead(n); w > 0 {
995 t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, increment: w})
996 }
997}
998
999// updateFlowControl updates the incoming flow control windows
1000// for the transport and the stream based on the current bdp
1001// estimation.
1002func (t *http2Client) updateFlowControl(n uint32) {
1003 t.mu.Lock()
1004 for _, s := range t.activeStreams {
1005 s.fc.newLimit(n)
1006 }
1007 t.mu.Unlock()
1008 updateIWS := func(interface{}) bool {
1009 t.initialWindowSize = int32(n)
1010 return true
1011 }
1012 t.controlBuf.executeAndPut(updateIWS, &outgoingWindowUpdate{streamID: 0, increment: t.fc.newLimit(n)})
1013 t.controlBuf.put(&outgoingSettings{
1014 ss: []http2.Setting{
1015 {
1016 ID: http2.SettingInitialWindowSize,
1017 Val: n,
1018 },
1019 },
1020 })
1021}
1022
1023func (t *http2Client) handleData(f *http2.DataFrame) {
1024 size := f.Header().Length
1025 var sendBDPPing bool
1026 if t.bdpEst != nil {
1027 sendBDPPing = t.bdpEst.add(size)
1028 }
1029 // Decouple connection's flow control from application's read.
1030 // An update on connection's flow control should not depend on
1031 // whether user application has read the data or not. Such a
1032 // restriction is already imposed on the stream's flow control,
1033 // and therefore the sender will be blocked anyways.
1034 // Decoupling the connection flow control will prevent other
1035 // active(fast) streams from starving in presence of slow or
1036 // inactive streams.
1037 //
1038 if w := t.fc.onData(size); w > 0 {
1039 t.controlBuf.put(&outgoingWindowUpdate{
1040 streamID: 0,
1041 increment: w,
1042 })
1043 }
1044 if sendBDPPing {
1045 // Avoid excessive ping detection (e.g. in an L7 proxy)
1046 // by sending a window update prior to the BDP ping.
1047
1048 if w := t.fc.reset(); w > 0 {
1049 t.controlBuf.put(&outgoingWindowUpdate{
1050 streamID: 0,
1051 increment: w,
1052 })
1053 }
1054
1055 t.controlBuf.put(bdpPing)
1056 }
1057 // Select the right stream to dispatch.
1058 s := t.getStream(f)
1059 if s == nil {
1060 return
1061 }
1062 if size > 0 {
1063 if err := s.fc.onData(size); err != nil {
1064 t.closeStream(s, io.EOF, true, http2.ErrCodeFlowControl, status.New(codes.Internal, err.Error()), nil, false)
1065 return
1066 }
1067 if f.Header().Flags.Has(http2.FlagDataPadded) {
1068 if w := s.fc.onRead(size - uint32(len(f.Data()))); w > 0 {
1069 t.controlBuf.put(&outgoingWindowUpdate{s.id, w})
1070 }
1071 }
1072 // TODO(bradfitz, zhaoq): A copy is required here because there is no
1073 // guarantee f.Data() is consumed before the arrival of next frame.
1074 // Can this copy be eliminated?
1075 if len(f.Data()) > 0 {
1076 buffer := t.bufferPool.get()
1077 buffer.Reset()
1078 buffer.Write(f.Data())
1079 s.write(recvMsg{buffer: buffer})
1080 }
1081 }
1082 // The server has closed the stream without sending trailers. Record that
1083 // the read direction is closed, and set the status appropriately.
khenaidoo5cb0d402021-12-08 14:09:16 -05001084 if f.StreamEnded() {
khenaidoo5fc5cea2021-08-11 17:39:16 -04001085 t.closeStream(s, io.EOF, false, http2.ErrCodeNo, status.New(codes.Internal, "server closed the stream without sending trailers"), nil, true)
1086 }
1087}
1088
1089func (t *http2Client) handleRSTStream(f *http2.RSTStreamFrame) {
1090 s := t.getStream(f)
1091 if s == nil {
1092 return
1093 }
1094 if f.ErrCode == http2.ErrCodeRefusedStream {
1095 // The stream was unprocessed by the server.
1096 atomic.StoreUint32(&s.unprocessed, 1)
1097 }
1098 statusCode, ok := http2ErrConvTab[f.ErrCode]
1099 if !ok {
1100 if logger.V(logLevel) {
1101 logger.Warningf("transport: http2Client.handleRSTStream found no mapped gRPC status for the received http2 error %v", f.ErrCode)
1102 }
1103 statusCode = codes.Unknown
1104 }
1105 if statusCode == codes.Canceled {
1106 if d, ok := s.ctx.Deadline(); ok && !d.After(time.Now()) {
1107 // Our deadline was already exceeded, and that was likely the cause
1108 // of this cancelation. Alter the status code accordingly.
1109 statusCode = codes.DeadlineExceeded
1110 }
1111 }
1112 t.closeStream(s, io.EOF, false, http2.ErrCodeNo, status.Newf(statusCode, "stream terminated by RST_STREAM with error code: %v", f.ErrCode), nil, false)
1113}
1114
1115func (t *http2Client) handleSettings(f *http2.SettingsFrame, isFirst bool) {
1116 if f.IsAck() {
1117 return
1118 }
1119 var maxStreams *uint32
1120 var ss []http2.Setting
1121 var updateFuncs []func()
1122 f.ForeachSetting(func(s http2.Setting) error {
1123 switch s.ID {
1124 case http2.SettingMaxConcurrentStreams:
1125 maxStreams = new(uint32)
1126 *maxStreams = s.Val
1127 case http2.SettingMaxHeaderListSize:
1128 updateFuncs = append(updateFuncs, func() {
1129 t.maxSendHeaderListSize = new(uint32)
1130 *t.maxSendHeaderListSize = s.Val
1131 })
1132 default:
1133 ss = append(ss, s)
1134 }
1135 return nil
1136 })
1137 if isFirst && maxStreams == nil {
1138 maxStreams = new(uint32)
1139 *maxStreams = math.MaxUint32
1140 }
1141 sf := &incomingSettings{
1142 ss: ss,
1143 }
1144 if maxStreams != nil {
1145 updateStreamQuota := func() {
1146 delta := int64(*maxStreams) - int64(t.maxConcurrentStreams)
1147 t.maxConcurrentStreams = *maxStreams
1148 t.streamQuota += delta
1149 if delta > 0 && t.waitingStreams > 0 {
1150 close(t.streamsQuotaAvailable) // wake all of them up.
1151 t.streamsQuotaAvailable = make(chan struct{}, 1)
1152 }
1153 }
1154 updateFuncs = append(updateFuncs, updateStreamQuota)
1155 }
1156 t.controlBuf.executeAndPut(func(interface{}) bool {
1157 for _, f := range updateFuncs {
1158 f()
1159 }
1160 return true
1161 }, sf)
1162}
1163
1164func (t *http2Client) handlePing(f *http2.PingFrame) {
1165 if f.IsAck() {
1166 // Maybe it's a BDP ping.
1167 if t.bdpEst != nil {
1168 t.bdpEst.calculate(f.Data)
1169 }
1170 return
1171 }
1172 pingAck := &ping{ack: true}
1173 copy(pingAck.data[:], f.Data[:])
1174 t.controlBuf.put(pingAck)
1175}
1176
1177func (t *http2Client) handleGoAway(f *http2.GoAwayFrame) {
1178 t.mu.Lock()
1179 if t.state == closing {
1180 t.mu.Unlock()
1181 return
1182 }
1183 if f.ErrCode == http2.ErrCodeEnhanceYourCalm {
1184 if logger.V(logLevel) {
1185 logger.Infof("Client received GoAway with http2.ErrCodeEnhanceYourCalm.")
1186 }
1187 }
1188 id := f.LastStreamID
1189 if id > 0 && id%2 == 0 {
1190 t.mu.Unlock()
1191 t.Close(connectionErrorf(true, nil, "received goaway with non-zero even-numbered numbered stream id: %v", id))
1192 return
1193 }
1194 // A client can receive multiple GoAways from the server (see
1195 // https://github.com/grpc/grpc-go/issues/1387). The idea is that the first
1196 // GoAway will be sent with an ID of MaxInt32 and the second GoAway will be
1197 // sent after an RTT delay with the ID of the last stream the server will
1198 // process.
1199 //
1200 // Therefore, when we get the first GoAway we don't necessarily close any
1201 // streams. While in case of second GoAway we close all streams created after
1202 // the GoAwayId. This way streams that were in-flight while the GoAway from
1203 // server was being sent don't get killed.
1204 select {
1205 case <-t.goAway: // t.goAway has been closed (i.e.,multiple GoAways).
1206 // If there are multiple GoAways the first one should always have an ID greater than the following ones.
1207 if id > t.prevGoAwayID {
1208 t.mu.Unlock()
1209 t.Close(connectionErrorf(true, nil, "received goaway with stream id: %v, which exceeds stream id of previous goaway: %v", id, t.prevGoAwayID))
1210 return
1211 }
1212 default:
1213 t.setGoAwayReason(f)
1214 close(t.goAway)
1215 t.controlBuf.put(&incomingGoAway{})
1216 // Notify the clientconn about the GOAWAY before we set the state to
1217 // draining, to allow the client to stop attempting to create streams
1218 // before disallowing new streams on this connection.
1219 t.onGoAway(t.goAwayReason)
1220 t.state = draining
1221 }
1222 // All streams with IDs greater than the GoAwayId
1223 // and smaller than the previous GoAway ID should be killed.
1224 upperLimit := t.prevGoAwayID
1225 if upperLimit == 0 { // This is the first GoAway Frame.
1226 upperLimit = math.MaxUint32 // Kill all streams after the GoAway ID.
1227 }
1228 for streamID, stream := range t.activeStreams {
1229 if streamID > id && streamID <= upperLimit {
1230 // The stream was unprocessed by the server.
1231 atomic.StoreUint32(&stream.unprocessed, 1)
1232 t.closeStream(stream, errStreamDrain, false, http2.ErrCodeNo, statusGoAway, nil, false)
1233 }
1234 }
1235 t.prevGoAwayID = id
1236 active := len(t.activeStreams)
1237 t.mu.Unlock()
1238 if active == 0 {
1239 t.Close(connectionErrorf(true, nil, "received goaway and there are no active streams"))
1240 }
1241}
1242
1243// setGoAwayReason sets the value of t.goAwayReason based
1244// on the GoAway frame received.
1245// It expects a lock on transport's mutext to be held by
1246// the caller.
1247func (t *http2Client) setGoAwayReason(f *http2.GoAwayFrame) {
1248 t.goAwayReason = GoAwayNoReason
1249 switch f.ErrCode {
1250 case http2.ErrCodeEnhanceYourCalm:
1251 if string(f.DebugData()) == "too_many_pings" {
1252 t.goAwayReason = GoAwayTooManyPings
1253 }
1254 }
1255 if len(f.DebugData()) == 0 {
1256 t.goAwayDebugMessage = fmt.Sprintf("code: %s", f.ErrCode)
1257 } else {
1258 t.goAwayDebugMessage = fmt.Sprintf("code: %s, debug data: %q", f.ErrCode, string(f.DebugData()))
1259 }
1260}
1261
1262func (t *http2Client) GetGoAwayReason() (GoAwayReason, string) {
1263 t.mu.Lock()
1264 defer t.mu.Unlock()
1265 return t.goAwayReason, t.goAwayDebugMessage
1266}
1267
1268func (t *http2Client) handleWindowUpdate(f *http2.WindowUpdateFrame) {
1269 t.controlBuf.put(&incomingWindowUpdate{
1270 streamID: f.Header().StreamID,
1271 increment: f.Increment,
1272 })
1273}
1274
1275// operateHeaders takes action on the decoded headers.
1276func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) {
1277 s := t.getStream(frame)
1278 if s == nil {
1279 return
1280 }
1281 endStream := frame.StreamEnded()
1282 atomic.StoreUint32(&s.bytesReceived, 1)
1283 initialHeader := atomic.LoadUint32(&s.headerChanClosed) == 0
1284
1285 if !initialHeader && !endStream {
1286 // As specified by gRPC over HTTP2, a HEADERS frame (and associated CONTINUATION frames) can only appear at the start or end of a stream. Therefore, second HEADERS frame must have EOS bit set.
1287 st := status.New(codes.Internal, "a HEADERS frame cannot appear in the middle of a stream")
1288 t.closeStream(s, st.Err(), true, http2.ErrCodeProtocol, st, nil, false)
1289 return
1290 }
1291
1292 // frame.Truncated is set to true when framer detects that the current header
1293 // list size hits MaxHeaderListSize limit.
1294 if frame.Truncated {
1295 se := status.New(codes.Internal, "peer header list size exceeded limit")
1296 t.closeStream(s, se.Err(), true, http2.ErrCodeFrameSize, se, nil, endStream)
1297 return
1298 }
1299
1300 var (
1301 // If a gRPC Response-Headers has already been received, then it means
1302 // that the peer is speaking gRPC and we are in gRPC mode.
1303 isGRPC = !initialHeader
1304 mdata = make(map[string][]string)
1305 contentTypeErr = "malformed header: missing HTTP content-type"
1306 grpcMessage string
1307 statusGen *status.Status
1308 recvCompress string
1309 httpStatusCode *int
1310 httpStatusErr string
1311 rawStatusCode = codes.Unknown
1312 // headerError is set if an error is encountered while parsing the headers
1313 headerError string
1314 )
1315
1316 if initialHeader {
1317 httpStatusErr = "malformed header: missing HTTP status"
1318 }
1319
1320 for _, hf := range frame.Fields {
1321 switch hf.Name {
1322 case "content-type":
1323 if _, validContentType := grpcutil.ContentSubtype(hf.Value); !validContentType {
1324 contentTypeErr = fmt.Sprintf("transport: received unexpected content-type %q", hf.Value)
1325 break
1326 }
1327 contentTypeErr = ""
1328 mdata[hf.Name] = append(mdata[hf.Name], hf.Value)
1329 isGRPC = true
1330 case "grpc-encoding":
1331 recvCompress = hf.Value
1332 case "grpc-status":
1333 code, err := strconv.ParseInt(hf.Value, 10, 32)
1334 if err != nil {
1335 se := status.New(codes.Internal, fmt.Sprintf("transport: malformed grpc-status: %v", err))
1336 t.closeStream(s, se.Err(), true, http2.ErrCodeProtocol, se, nil, endStream)
1337 return
1338 }
1339 rawStatusCode = codes.Code(uint32(code))
1340 case "grpc-message":
1341 grpcMessage = decodeGrpcMessage(hf.Value)
1342 case "grpc-status-details-bin":
1343 var err error
1344 statusGen, err = decodeGRPCStatusDetails(hf.Value)
1345 if err != nil {
1346 headerError = fmt.Sprintf("transport: malformed grpc-status-details-bin: %v", err)
1347 }
1348 case ":status":
1349 if hf.Value == "200" {
1350 httpStatusErr = ""
1351 statusCode := 200
1352 httpStatusCode = &statusCode
1353 break
1354 }
1355
1356 c, err := strconv.ParseInt(hf.Value, 10, 32)
1357 if err != nil {
1358 se := status.New(codes.Internal, fmt.Sprintf("transport: malformed http-status: %v", err))
1359 t.closeStream(s, se.Err(), true, http2.ErrCodeProtocol, se, nil, endStream)
1360 return
1361 }
1362 statusCode := int(c)
1363 httpStatusCode = &statusCode
1364
1365 httpStatusErr = fmt.Sprintf(
1366 "unexpected HTTP status code received from server: %d (%s)",
1367 statusCode,
1368 http.StatusText(statusCode),
1369 )
1370 default:
1371 if isReservedHeader(hf.Name) && !isWhitelistedHeader(hf.Name) {
1372 break
1373 }
1374 v, err := decodeMetadataHeader(hf.Name, hf.Value)
1375 if err != nil {
1376 headerError = fmt.Sprintf("transport: malformed %s: %v", hf.Name, err)
1377 logger.Warningf("Failed to decode metadata header (%q, %q): %v", hf.Name, hf.Value, err)
1378 break
1379 }
1380 mdata[hf.Name] = append(mdata[hf.Name], v)
1381 }
1382 }
1383
1384 if !isGRPC || httpStatusErr != "" {
1385 var code = codes.Internal // when header does not include HTTP status, return INTERNAL
1386
1387 if httpStatusCode != nil {
1388 var ok bool
1389 code, ok = HTTPStatusConvTab[*httpStatusCode]
1390 if !ok {
1391 code = codes.Unknown
1392 }
1393 }
1394 var errs []string
1395 if httpStatusErr != "" {
1396 errs = append(errs, httpStatusErr)
1397 }
1398 if contentTypeErr != "" {
1399 errs = append(errs, contentTypeErr)
1400 }
1401 // Verify the HTTP response is a 200.
1402 se := status.New(code, strings.Join(errs, "; "))
1403 t.closeStream(s, se.Err(), true, http2.ErrCodeProtocol, se, nil, endStream)
1404 return
1405 }
1406
1407 if headerError != "" {
1408 se := status.New(codes.Internal, headerError)
1409 t.closeStream(s, se.Err(), true, http2.ErrCodeProtocol, se, nil, endStream)
1410 return
1411 }
1412
1413 isHeader := false
khenaidoo5fc5cea2021-08-11 17:39:16 -04001414
1415 // If headerChan hasn't been closed yet
1416 if atomic.CompareAndSwapUint32(&s.headerChanClosed, 0, 1) {
1417 s.headerValid = true
1418 if !endStream {
1419 // HEADERS frame block carries a Response-Headers.
1420 isHeader = true
1421 // These values can be set without any synchronization because
1422 // stream goroutine will read it only after seeing a closed
1423 // headerChan which we'll close after setting this.
1424 s.recvCompress = recvCompress
1425 if len(mdata) > 0 {
1426 s.header = mdata
1427 }
1428 } else {
1429 // HEADERS frame block carries a Trailers-Only.
1430 s.noHeaders = true
1431 }
1432 close(s.headerChan)
1433 }
1434
khenaidoo5cb0d402021-12-08 14:09:16 -05001435 if t.statsHandler != nil {
1436 if isHeader {
1437 inHeader := &stats.InHeader{
1438 Client: true,
1439 WireLength: int(frame.Header().Length),
1440 Header: metadata.MD(mdata).Copy(),
1441 Compression: s.recvCompress,
1442 }
1443 t.statsHandler.HandleRPC(s.ctx, inHeader)
1444 } else {
1445 inTrailer := &stats.InTrailer{
1446 Client: true,
1447 WireLength: int(frame.Header().Length),
1448 Trailer: metadata.MD(mdata).Copy(),
1449 }
1450 t.statsHandler.HandleRPC(s.ctx, inTrailer)
1451 }
1452 }
1453
khenaidoo5fc5cea2021-08-11 17:39:16 -04001454 if !endStream {
1455 return
1456 }
1457
1458 if statusGen == nil {
1459 statusGen = status.New(rawStatusCode, grpcMessage)
1460 }
1461
1462 // if client received END_STREAM from server while stream was still active, send RST_STREAM
1463 rst := s.getState() == streamActive
1464 t.closeStream(s, io.EOF, rst, http2.ErrCodeNo, statusGen, mdata, true)
1465}
1466
1467// reader runs as a separate goroutine in charge of reading data from network
1468// connection.
1469//
1470// TODO(zhaoq): currently one reader per transport. Investigate whether this is
1471// optimal.
1472// TODO(zhaoq): Check the validity of the incoming frame sequence.
1473func (t *http2Client) reader() {
1474 defer close(t.readerDone)
1475 // Check the validity of server preface.
1476 frame, err := t.framer.fr.ReadFrame()
1477 if err != nil {
1478 err = connectionErrorf(true, err, "error reading server preface: %v", err)
1479 t.Close(err) // this kicks off resetTransport, so must be last before return
1480 return
1481 }
1482 t.conn.SetReadDeadline(time.Time{}) // reset deadline once we get the settings frame (we didn't time out, yay!)
1483 if t.keepaliveEnabled {
1484 atomic.StoreInt64(&t.lastRead, time.Now().UnixNano())
1485 }
1486 sf, ok := frame.(*http2.SettingsFrame)
1487 if !ok {
1488 // this kicks off resetTransport, so must be last before return
1489 t.Close(connectionErrorf(true, nil, "initial http2 frame from server is not a settings frame: %T", frame))
1490 return
1491 }
1492 t.onPrefaceReceipt()
1493 t.handleSettings(sf, true)
1494
1495 // loop to keep reading incoming messages on this transport.
1496 for {
1497 t.controlBuf.throttle()
1498 frame, err := t.framer.fr.ReadFrame()
1499 if t.keepaliveEnabled {
1500 atomic.StoreInt64(&t.lastRead, time.Now().UnixNano())
1501 }
1502 if err != nil {
1503 // Abort an active stream if the http2.Framer returns a
1504 // http2.StreamError. This can happen only if the server's response
1505 // is malformed http2.
1506 if se, ok := err.(http2.StreamError); ok {
1507 t.mu.Lock()
1508 s := t.activeStreams[se.StreamID]
1509 t.mu.Unlock()
1510 if s != nil {
1511 // use error detail to provide better err message
1512 code := http2ErrConvTab[se.Code]
1513 errorDetail := t.framer.fr.ErrorDetail()
1514 var msg string
1515 if errorDetail != nil {
1516 msg = errorDetail.Error()
1517 } else {
1518 msg = "received invalid frame"
1519 }
1520 t.closeStream(s, status.Error(code, msg), true, http2.ErrCodeProtocol, status.New(code, msg), nil, false)
1521 }
1522 continue
1523 } else {
1524 // Transport error.
1525 t.Close(connectionErrorf(true, err, "error reading from server: %v", err))
1526 return
1527 }
1528 }
1529 switch frame := frame.(type) {
1530 case *http2.MetaHeadersFrame:
1531 t.operateHeaders(frame)
1532 case *http2.DataFrame:
1533 t.handleData(frame)
1534 case *http2.RSTStreamFrame:
1535 t.handleRSTStream(frame)
1536 case *http2.SettingsFrame:
1537 t.handleSettings(frame, false)
1538 case *http2.PingFrame:
1539 t.handlePing(frame)
1540 case *http2.GoAwayFrame:
1541 t.handleGoAway(frame)
1542 case *http2.WindowUpdateFrame:
1543 t.handleWindowUpdate(frame)
1544 default:
1545 if logger.V(logLevel) {
1546 logger.Errorf("transport: http2Client.reader got unhandled frame type %v.", frame)
1547 }
1548 }
1549 }
1550}
1551
1552func minTime(a, b time.Duration) time.Duration {
1553 if a < b {
1554 return a
1555 }
1556 return b
1557}
1558
1559// keepalive running in a separate goroutune makes sure the connection is alive by sending pings.
1560func (t *http2Client) keepalive() {
1561 p := &ping{data: [8]byte{}}
1562 // True iff a ping has been sent, and no data has been received since then.
1563 outstandingPing := false
1564 // Amount of time remaining before which we should receive an ACK for the
1565 // last sent ping.
1566 timeoutLeft := time.Duration(0)
1567 // Records the last value of t.lastRead before we go block on the timer.
1568 // This is required to check for read activity since then.
1569 prevNano := time.Now().UnixNano()
1570 timer := time.NewTimer(t.kp.Time)
1571 for {
1572 select {
1573 case <-timer.C:
1574 lastRead := atomic.LoadInt64(&t.lastRead)
1575 if lastRead > prevNano {
1576 // There has been read activity since the last time we were here.
1577 outstandingPing = false
1578 // Next timer should fire at kp.Time seconds from lastRead time.
1579 timer.Reset(time.Duration(lastRead) + t.kp.Time - time.Duration(time.Now().UnixNano()))
1580 prevNano = lastRead
1581 continue
1582 }
1583 if outstandingPing && timeoutLeft <= 0 {
1584 t.Close(connectionErrorf(true, nil, "keepalive ping failed to receive ACK within timeout"))
1585 return
1586 }
1587 t.mu.Lock()
1588 if t.state == closing {
1589 // If the transport is closing, we should exit from the
1590 // keepalive goroutine here. If not, we could have a race
1591 // between the call to Signal() from Close() and the call to
1592 // Wait() here, whereby the keepalive goroutine ends up
1593 // blocking on the condition variable which will never be
1594 // signalled again.
1595 t.mu.Unlock()
1596 return
1597 }
1598 if len(t.activeStreams) < 1 && !t.kp.PermitWithoutStream {
1599 // If a ping was sent out previously (because there were active
1600 // streams at that point) which wasn't acked and its timeout
1601 // hadn't fired, but we got here and are about to go dormant,
1602 // we should make sure that we unconditionally send a ping once
1603 // we awaken.
1604 outstandingPing = false
1605 t.kpDormant = true
1606 t.kpDormancyCond.Wait()
1607 }
1608 t.kpDormant = false
1609 t.mu.Unlock()
1610
1611 // We get here either because we were dormant and a new stream was
1612 // created which unblocked the Wait() call, or because the
1613 // keepalive timer expired. In both cases, we need to send a ping.
1614 if !outstandingPing {
1615 if channelz.IsOn() {
1616 atomic.AddInt64(&t.czData.kpCount, 1)
1617 }
1618 t.controlBuf.put(p)
1619 timeoutLeft = t.kp.Timeout
1620 outstandingPing = true
1621 }
1622 // The amount of time to sleep here is the minimum of kp.Time and
1623 // timeoutLeft. This will ensure that we wait only for kp.Time
1624 // before sending out the next ping (for cases where the ping is
1625 // acked).
1626 sleepDuration := minTime(t.kp.Time, timeoutLeft)
1627 timeoutLeft -= sleepDuration
1628 timer.Reset(sleepDuration)
1629 case <-t.ctx.Done():
1630 if !timer.Stop() {
1631 <-timer.C
1632 }
1633 return
1634 }
1635 }
1636}
1637
1638func (t *http2Client) Error() <-chan struct{} {
1639 return t.ctx.Done()
1640}
1641
1642func (t *http2Client) GoAway() <-chan struct{} {
1643 return t.goAway
1644}
1645
1646func (t *http2Client) ChannelzMetric() *channelz.SocketInternalMetric {
1647 s := channelz.SocketInternalMetric{
1648 StreamsStarted: atomic.LoadInt64(&t.czData.streamsStarted),
1649 StreamsSucceeded: atomic.LoadInt64(&t.czData.streamsSucceeded),
1650 StreamsFailed: atomic.LoadInt64(&t.czData.streamsFailed),
1651 MessagesSent: atomic.LoadInt64(&t.czData.msgSent),
1652 MessagesReceived: atomic.LoadInt64(&t.czData.msgRecv),
1653 KeepAlivesSent: atomic.LoadInt64(&t.czData.kpCount),
1654 LastLocalStreamCreatedTimestamp: time.Unix(0, atomic.LoadInt64(&t.czData.lastStreamCreatedTime)),
1655 LastMessageSentTimestamp: time.Unix(0, atomic.LoadInt64(&t.czData.lastMsgSentTime)),
1656 LastMessageReceivedTimestamp: time.Unix(0, atomic.LoadInt64(&t.czData.lastMsgRecvTime)),
1657 LocalFlowControlWindow: int64(t.fc.getSize()),
1658 SocketOptions: channelz.GetSocketOption(t.conn),
1659 LocalAddr: t.localAddr,
1660 RemoteAddr: t.remoteAddr,
1661 // RemoteName :
1662 }
1663 if au, ok := t.authInfo.(credentials.ChannelzSecurityInfo); ok {
1664 s.Security = au.GetSecurityValue()
1665 }
1666 s.RemoteFlowControlWindow = t.getOutFlowWindow()
1667 return &s
1668}
1669
1670func (t *http2Client) RemoteAddr() net.Addr { return t.remoteAddr }
1671
1672func (t *http2Client) IncrMsgSent() {
1673 atomic.AddInt64(&t.czData.msgSent, 1)
1674 atomic.StoreInt64(&t.czData.lastMsgSentTime, time.Now().UnixNano())
1675}
1676
1677func (t *http2Client) IncrMsgRecv() {
1678 atomic.AddInt64(&t.czData.msgRecv, 1)
1679 atomic.StoreInt64(&t.czData.lastMsgRecvTime, time.Now().UnixNano())
1680}
1681
1682func (t *http2Client) getOutFlowWindow() int64 {
1683 resp := make(chan uint32, 1)
1684 timer := time.NewTimer(time.Second)
1685 defer timer.Stop()
1686 t.controlBuf.put(&outFlowControlSizeRequest{resp})
1687 select {
1688 case sz := <-resp:
1689 return int64(sz)
1690 case <-t.ctxDone:
1691 return -1
1692 case <-timer.C:
1693 return -2
1694 }
1695}