3 * Copyright 2016 gRPC authors.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 // This file is the implementation of a gRPC server using HTTP/2 which
20 // uses the standard Go http2 Server implementation (via the
21 // http.Handler interface), rather than speaking low-level HTTP/2
22 // frames itself. It is the implementation of *grpc.Server.ServeHTTP.
36 "golang.org/x/net/context"
37 "golang.org/x/net/http2"
38 "google.golang.org/grpc/codes"
39 "google.golang.org/grpc/credentials"
40 "google.golang.org/grpc/metadata"
41 "google.golang.org/grpc/peer"
42 "google.golang.org/grpc/status"
45 // NewServerHandlerTransport returns a ServerTransport handling gRPC
46 // from inside an http.Handler. It requires that the http Server
48 func NewServerHandlerTransport(w http.ResponseWriter, r *http.Request) (ServerTransport, error) {
49 if r.ProtoMajor != 2 {
50 return nil, errors.New("gRPC requires HTTP/2")
52 if r.Method != "POST" {
53 return nil, errors.New("invalid gRPC request method")
55 if !validContentType(r.Header.Get("Content-Type")) {
56 return nil, errors.New("invalid gRPC request content-type")
58 if _, ok := w.(http.Flusher); !ok {
59 return nil, errors.New("gRPC requires a ResponseWriter supporting http.Flusher")
61 if _, ok := w.(http.CloseNotifier); !ok {
62 return nil, errors.New("gRPC requires a ResponseWriter supporting http.CloseNotifier")
65 st := &serverHandlerTransport{
68 closedCh: make(chan struct{}),
69 writes: make(chan func()),
72 if v := r.Header.Get("grpc-timeout"); v != "" {
73 to, err := decodeTimeout(v)
75 return nil, streamErrorf(codes.Internal, "malformed time-out: %v", err)
83 metakv = append(metakv, ":authority", r.Host)
85 for k, vv := range r.Header {
86 k = strings.ToLower(k)
87 if isReservedHeader(k) && !isWhitelistedPseudoHeader(k) {
90 for _, v := range vv {
91 v, err := decodeMetadataHeader(k, v)
93 return nil, streamErrorf(codes.InvalidArgument, "malformed binary metadata: %v", err)
95 metakv = append(metakv, k, v)
98 st.headerMD = metadata.Pairs(metakv...)
103 // serverHandlerTransport is an implementation of ServerTransport
104 // which replies to exactly one gRPC request (exactly one HTTP request),
105 // using the net/http.Handler interface. This http.Handler is guaranteed
106 // at this point to be speaking over HTTP/2, so it's able to speak valid
108 type serverHandlerTransport struct {
109 rw http.ResponseWriter
112 timeout time.Duration
113 didCommonHeaders bool
118 closedCh chan struct{} // closed on Close
120 // writes is a channel of code to run serialized in the
121 // ServeHTTP (HandleStreams) goroutine. The channel is closed
122 // when WriteStatus is called.
126 func (ht *serverHandlerTransport) Close() error {
127 ht.closeOnce.Do(ht.closeCloseChanOnce)
131 func (ht *serverHandlerTransport) closeCloseChanOnce() { close(ht.closedCh) }
133 func (ht *serverHandlerTransport) RemoteAddr() net.Addr { return strAddr(ht.req.RemoteAddr) }
135 // strAddr is a net.Addr backed by either a TCP "ip:port" string, or
136 // the empty string if unknown.
139 func (a strAddr) Network() string {
141 // Per the documentation on net/http.Request.RemoteAddr, if this is
142 // set, it's set to the IP:port of the peer (hence, TCP):
143 // https://golang.org/pkg/net/http/#Request
145 // If we want to support Unix sockets later, we can
146 // add our own grpc-specific convention within the
147 // grpc codebase to set RemoteAddr to a different
148 // format, or probably better: we can attach it to the
149 // context and use that from serverHandlerTransport.RemoteAddr.
155 func (a strAddr) String() string { return string(a) }
157 // do runs fn in the ServeHTTP goroutine.
158 func (ht *serverHandlerTransport) do(fn func()) error {
159 // Avoid a panic writing to closed channel. Imperfect but maybe good enough.
162 return ErrConnClosing
165 case ht.writes <- fn:
168 return ErrConnClosing
174 func (ht *serverHandlerTransport) WriteStatus(s *Stream, st *status.Status) error {
175 err := ht.do(func() {
176 ht.writeCommonHeaders(s)
178 // And flush, in case no header or body has been sent yet.
179 // This forces a separation of headers and trailers if this is the
180 // first call (for example, in end2end tests's TestNoService).
181 ht.rw.(http.Flusher).Flush()
184 h.Set("Grpc-Status", fmt.Sprintf("%d", st.Code()))
185 if m := st.Message(); m != "" {
186 h.Set("Grpc-Message", encodeGrpcMessage(m))
189 // TODO: Support Grpc-Status-Details-Bin
191 if md := s.Trailer(); len(md) > 0 {
192 for k, vv := range md {
193 // Clients don't tolerate reading restricted headers after some non restricted ones were sent.
194 if isReservedHeader(k) {
197 for _, v := range vv {
198 // http2 ResponseWriter mechanism to send undeclared Trailers after
199 // the headers have possibly been written.
200 h.Add(http2.TrailerPrefix+k, encodeMetadataHeader(k, v))
209 // writeCommonHeaders sets common headers on the first write
210 // call (Write, WriteHeader, or WriteStatus).
211 func (ht *serverHandlerTransport) writeCommonHeaders(s *Stream) {
212 if ht.didCommonHeaders {
215 ht.didCommonHeaders = true
218 h["Date"] = nil // suppress Date to make tests happy; TODO: restore
219 h.Set("Content-Type", "application/grpc")
221 // Predeclare trailers we'll set later in WriteStatus (after the body).
222 // This is a SHOULD in the HTTP RFC, and the way you add (known)
223 // Trailers per the net/http.ResponseWriter contract.
224 // See https://golang.org/pkg/net/http/#ResponseWriter
225 // and https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
226 h.Add("Trailer", "Grpc-Status")
227 h.Add("Trailer", "Grpc-Message")
228 // TODO: Support Grpc-Status-Details-Bin
230 if s.sendCompress != "" {
231 h.Set("Grpc-Encoding", s.sendCompress)
235 func (ht *serverHandlerTransport) Write(s *Stream, data []byte, opts *Options) error {
236 return ht.do(func() {
237 ht.writeCommonHeaders(s)
240 ht.rw.(http.Flusher).Flush()
245 func (ht *serverHandlerTransport) WriteHeader(s *Stream, md metadata.MD) error {
246 return ht.do(func() {
247 ht.writeCommonHeaders(s)
249 for k, vv := range md {
250 // Clients don't tolerate reading restricted headers after some non restricted ones were sent.
251 if isReservedHeader(k) {
254 for _, v := range vv {
255 v = encodeMetadataHeader(k, v)
259 ht.rw.WriteHeader(200)
260 ht.rw.(http.Flusher).Flush()
264 func (ht *serverHandlerTransport) HandleStreams(startStream func(*Stream), traceCtx func(context.Context, string) context.Context) {
265 // With this transport type there will be exactly 1 stream: this HTTP request.
267 var ctx context.Context
268 var cancel context.CancelFunc
270 ctx, cancel = context.WithTimeout(context.Background(), ht.timeout)
272 ctx, cancel = context.WithCancel(context.Background())
275 // requestOver is closed when either the request's context is done
276 // or the status has been written via WriteStatus.
277 requestOver := make(chan struct{})
279 // clientGone receives a single value if peer is gone, either
280 // because the underlying connection is dead or because the
281 // peer sends an http2 RST_STREAM.
282 clientGone := ht.rw.(http.CloseNotifier).CloseNotify()
297 requestRead: func(int) {},
299 buf: newRecvBuffer(),
301 method: req.URL.Path,
302 recvCompress: req.Header.Get("grpc-encoding"),
305 Addr: ht.RemoteAddr(),
308 pr.AuthInfo = credentials.TLSInfo{State: *req.TLS}
310 ctx = metadata.NewIncomingContext(ctx, ht.headerMD)
311 ctx = peer.NewContext(ctx, pr)
312 s.ctx = newContextWithStream(ctx, s)
313 s.trReader = &transportReader{
314 reader: &recvBufferReader{ctx: s.ctx, recv: s.buf},
315 windowHandler: func(int) {},
318 // readerDone is closed when the Body.Read-ing goroutine exits.
319 readerDone := make(chan struct{})
321 defer close(readerDone)
323 // TODO: minimize garbage, optimize recvBuffer code/ownership
324 const readSize = 8196
325 for buf := make([]byte, readSize); ; {
326 n, err := req.Body.Read(buf)
328 s.buf.put(recvMsg{data: buf[:n:n]})
332 s.buf.put(recvMsg{err: mapRecvMsgError(err)})
336 buf = make([]byte, readSize)
341 // startStream is provided by the *grpc.Server's serveStreams.
342 // It starts a goroutine serving s and exits immediately.
343 // The goroutine that is started is the one that then calls
344 // into ht, calling WriteHeader, Write, WriteStatus, Close, etc.
350 // Wait for reading goroutine to finish.
355 func (ht *serverHandlerTransport) runStream() {
358 case fn, ok := <-ht.writes:
369 func (ht *serverHandlerTransport) Drain() {
370 panic("Drain() is not implemented")
373 // mapRecvMsgError returns the non-nil err into the appropriate
374 // error value as expected by callers of *grpc.parser.recvMsg.
375 // In particular, in can only be:
377 // * io.ErrUnexpectedEOF
378 // * of type transport.ConnectionError
379 // * of type transport.StreamError
380 func mapRecvMsgError(err error) error {
381 if err == io.EOF || err == io.ErrUnexpectedEOF {
384 if se, ok := err.(http2.StreamError); ok {
385 if code, ok := http2ErrConvTab[se.Code]; ok {
392 return connectionErrorf(true, err, err.Error())