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