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