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