Debian Codegraph @

vendor/google.golang.org/grpc/transport/handler_server.go

raw
1 /*
2 *
3 * Copyright 2016 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 // 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.
23
24 package transport
25
26 import (
27 "errors"
28 "fmt"
29 "io"
30 "net"
31 "net/http"
32 "strings"
33 "sync"
34 "time"
35
36 "github.com/golang/protobuf/proto"
37 "golang.org/x/net/context"
38 "golang.org/x/net/http2"
39 "google.golang.org/grpc/codes"
40 "google.golang.org/grpc/credentials"
41 "google.golang.org/grpc/metadata"
42 "google.golang.org/grpc/peer"
43 "google.golang.org/grpc/status"
44 )
45
46 // NewServerHandlerTransport returns a ServerTransport handling gRPC
47 // from inside an http.Handler. It requires that the http Server
48 // supports HTTP/2.
49 func NewServerHandlerTransport(w http.ResponseWriter, r *http.Request) (ServerTransport, error) {
50 if r.ProtoMajor != 2 {
51 return nil, errors.New("gRPC requires HTTP/2")
52 }
53 if r.Method != "POST" {
54 return nil, errors.New("invalid gRPC request method")
55 }
56 if !validContentType(r.Header.Get("Content-Type")) {
57 return nil, errors.New("invalid gRPC request content-type")
58 }
59 if _, ok := w.(http.Flusher); !ok {
60 return nil, errors.New("gRPC requires a ResponseWriter supporting http.Flusher")
61 }
62 if _, ok := w.(http.CloseNotifier); !ok {
63 return nil, errors.New("gRPC requires a ResponseWriter supporting http.CloseNotifier")
64 }
65
66 st := &serverHandlerTransport{
67 rw: w,
68 req: r,
69 closedCh: make(chan struct{}),
70 writes: make(chan func()),
71 }
72
73 if v := r.Header.Get("grpc-timeout"); v != "" {
74 to, err := decodeTimeout(v)
75 if err != nil {
76 return nil, streamErrorf(codes.Internal, "malformed time-out: %v", err)
77 }
78 st.timeoutSet = true
79 st.timeout = to
80 }
81
82 var metakv []string
83 if r.Host != "" {
84 metakv = append(metakv, ":authority", r.Host)
85 }
86 for k, vv := range r.Header {
87 k = strings.ToLower(k)
88 if isReservedHeader(k) && !isWhitelistedPseudoHeader(k) {
89 continue
90 }
91 for _, v := range vv {
92 v, err := decodeMetadataHeader(k, v)
93 if err != nil {
94 return nil, streamErrorf(codes.InvalidArgument, "malformed binary metadata: %v", err)
95 }
96 metakv = append(metakv, k, v)
97 }
98 }
99 st.headerMD = metadata.Pairs(metakv...)
100
101 return st, nil
102 }
103
104 // serverHandlerTransport is an implementation of ServerTransport
105 // which replies to exactly one gRPC request (exactly one HTTP request),
106 // using the net/http.Handler interface. This http.Handler is guaranteed
107 // at this point to be speaking over HTTP/2, so it's able to speak valid
108 // gRPC.
109 type serverHandlerTransport struct {
110 rw http.ResponseWriter
111 req *http.Request
112 timeoutSet bool
113 timeout time.Duration
114 didCommonHeaders bool
115
116 headerMD metadata.MD
117
118 closeOnce sync.Once
119 closedCh chan struct{} // closed on Close
120
121 // writes is a channel of code to run serialized in the
122 // ServeHTTP (HandleStreams) goroutine. The channel is closed
123 // when WriteStatus is called.
124 writes chan func()
125
126 // block concurrent WriteStatus calls
127 // e.g. grpc/(*serverStream).SendMsg/RecvMsg
128 writeStatusMu sync.Mutex
129 }
130
131 func (ht *serverHandlerTransport) Close() error {
132 ht.closeOnce.Do(ht.closeCloseChanOnce)
133 return nil
134 }
135
136 func (ht *serverHandlerTransport) closeCloseChanOnce() { close(ht.closedCh) }
137
138 func (ht *serverHandlerTransport) RemoteAddr() net.Addr { return strAddr(ht.req.RemoteAddr) }
139
140 // strAddr is a net.Addr backed by either a TCP "ip:port" string, or
141 // the empty string if unknown.
142 type strAddr string
143
144 func (a strAddr) Network() string {
145 if a != "" {
146 // Per the documentation on net/http.Request.RemoteAddr, if this is
147 // set, it's set to the IP:port of the peer (hence, TCP):
148 // https://golang.org/pkg/net/http/#Request
149 //
150 // If we want to support Unix sockets later, we can
151 // add our own grpc-specific convention within the
152 // grpc codebase to set RemoteAddr to a different
153 // format, or probably better: we can attach it to the
154 // context and use that from serverHandlerTransport.RemoteAddr.
155 return "tcp"
156 }
157 return ""
158 }
159
160 func (a strAddr) String() string { return string(a) }
161
162 // do runs fn in the ServeHTTP goroutine.
163 func (ht *serverHandlerTransport) do(fn func()) error {
164 // Avoid a panic writing to closed channel. Imperfect but maybe good enough.
165 select {
166 case <-ht.closedCh:
167 return ErrConnClosing
168 default:
169 select {
170 case ht.writes <- fn:
171 return nil
172 case <-ht.closedCh:
173 return ErrConnClosing
174 }
175 }
176 }
177
178 func (ht *serverHandlerTransport) WriteStatus(s *Stream, st *status.Status) error {
179 ht.writeStatusMu.Lock()
180 defer ht.writeStatusMu.Unlock()
181
182 err := ht.do(func() {
183 ht.writeCommonHeaders(s)
184
185 // And flush, in case no header or body has been sent yet.
186 // This forces a separation of headers and trailers if this is the
187 // first call (for example, in end2end tests's TestNoService).
188 ht.rw.(http.Flusher).Flush()
189
190 h := ht.rw.Header()
191 h.Set("Grpc-Status", fmt.Sprintf("%d", st.Code()))
192 if m := st.Message(); m != "" {
193 h.Set("Grpc-Message", encodeGrpcMessage(m))
194 }
195
196 if p := st.Proto(); p != nil && len(p.Details) > 0 {
197 stBytes, err := proto.Marshal(p)
198 if err != nil {
199 // TODO: return error instead, when callers are able to handle it.
200 panic(err)
201 }
202
203 h.Set("Grpc-Status-Details-Bin", encodeBinHeader(stBytes))
204 }
205
206 if md := s.Trailer(); len(md) > 0 {
207 for k, vv := range md {
208 // Clients don't tolerate reading restricted headers after some non restricted ones were sent.
209 if isReservedHeader(k) {
210 continue
211 }
212 for _, v := range vv {
213 // http2 ResponseWriter mechanism to send undeclared Trailers after
214 // the headers have possibly been written.
215 h.Add(http2.TrailerPrefix+k, encodeMetadataHeader(k, v))
216 }
217 }
218 }
219 })
220
221 if err == nil { // transport has not been closed
222 ht.Close()
223 close(ht.writes)
224 }
225 return err
226 }
227
228 // writeCommonHeaders sets common headers on the first write
229 // call (Write, WriteHeader, or WriteStatus).
230 func (ht *serverHandlerTransport) writeCommonHeaders(s *Stream) {
231 if ht.didCommonHeaders {
232 return
233 }
234 ht.didCommonHeaders = true
235
236 h := ht.rw.Header()
237 h["Date"] = nil // suppress Date to make tests happy; TODO: restore
238 h.Set("Content-Type", "application/grpc")
239
240 // Predeclare trailers we'll set later in WriteStatus (after the body).
241 // This is a SHOULD in the HTTP RFC, and the way you add (known)
242 // Trailers per the net/http.ResponseWriter contract.
243 // See https://golang.org/pkg/net/http/#ResponseWriter
244 // and https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
245 h.Add("Trailer", "Grpc-Status")
246 h.Add("Trailer", "Grpc-Message")
247 h.Add("Trailer", "Grpc-Status-Details-Bin")
248
249 if s.sendCompress != "" {
250 h.Set("Grpc-Encoding", s.sendCompress)
251 }
252 }
253
254 func (ht *serverHandlerTransport) Write(s *Stream, hdr []byte, data []byte, opts *Options) error {
255 return ht.do(func() {
256 ht.writeCommonHeaders(s)
257 ht.rw.Write(hdr)
258 ht.rw.Write(data)
259 if !opts.Delay {
260 ht.rw.(http.Flusher).Flush()
261 }
262 })
263 }
264
265 func (ht *serverHandlerTransport) WriteHeader(s *Stream, md metadata.MD) error {
266 return ht.do(func() {
267 ht.writeCommonHeaders(s)
268 h := ht.rw.Header()
269 for k, vv := range md {
270 // Clients don't tolerate reading restricted headers after some non restricted ones were sent.
271 if isReservedHeader(k) {
272 continue
273 }
274 for _, v := range vv {
275 v = encodeMetadataHeader(k, v)
276 h.Add(k, v)
277 }
278 }
279 ht.rw.WriteHeader(200)
280 ht.rw.(http.Flusher).Flush()
281 })
282 }
283
284 func (ht *serverHandlerTransport) HandleStreams(startStream func(*Stream), traceCtx func(context.Context, string) context.Context) {
285 // With this transport type there will be exactly 1 stream: this HTTP request.
286
287 var ctx context.Context
288 var cancel context.CancelFunc
289 if ht.timeoutSet {
290 ctx, cancel = context.WithTimeout(context.Background(), ht.timeout)
291 } else {
292 ctx, cancel = context.WithCancel(context.Background())
293 }
294
295 // requestOver is closed when either the request's context is done
296 // or the status has been written via WriteStatus.
297 requestOver := make(chan struct{})
298
299 // clientGone receives a single value if peer is gone, either
300 // because the underlying connection is dead or because the
301 // peer sends an http2 RST_STREAM.
302 clientGone := ht.rw.(http.CloseNotifier).CloseNotify()
303 go func() {
304 select {
305 case <-requestOver:
306 return
307 case <-ht.closedCh:
308 case <-clientGone:
309 }
310 cancel()
311 }()
312
313 req := ht.req
314
315 s := &Stream{
316 id: 0, // irrelevant
317 requestRead: func(int) {},
318 cancel: cancel,
319 buf: newRecvBuffer(),
320 st: ht,
321 method: req.URL.Path,
322 recvCompress: req.Header.Get("grpc-encoding"),
323 }
324 pr := &peer.Peer{
325 Addr: ht.RemoteAddr(),
326 }
327 if req.TLS != nil {
328 pr.AuthInfo = credentials.TLSInfo{State: *req.TLS}
329 }
330 ctx = metadata.NewIncomingContext(ctx, ht.headerMD)
331 ctx = peer.NewContext(ctx, pr)
332 s.ctx = newContextWithStream(ctx, s)
333 s.trReader = &transportReader{
334 reader: &recvBufferReader{ctx: s.ctx, recv: s.buf},
335 windowHandler: func(int) {},
336 }
337
338 // readerDone is closed when the Body.Read-ing goroutine exits.
339 readerDone := make(chan struct{})
340 go func() {
341 defer close(readerDone)
342
343 // TODO: minimize garbage, optimize recvBuffer code/ownership
344 const readSize = 8196
345 for buf := make([]byte, readSize); ; {
346 n, err := req.Body.Read(buf)
347 if n > 0 {
348 s.buf.put(recvMsg{data: buf[:n:n]})
349 buf = buf[n:]
350 }
351 if err != nil {
352 s.buf.put(recvMsg{err: mapRecvMsgError(err)})
353 return
354 }
355 if len(buf) == 0 {
356 buf = make([]byte, readSize)
357 }
358 }
359 }()
360
361 // startStream is provided by the *grpc.Server's serveStreams.
362 // It starts a goroutine serving s and exits immediately.
363 // The goroutine that is started is the one that then calls
364 // into ht, calling WriteHeader, Write, WriteStatus, Close, etc.
365 startStream(s)
366
367 ht.runStream()
368 close(requestOver)
369
370 // Wait for reading goroutine to finish.
371 req.Body.Close()
372 <-readerDone
373 }
374
375 func (ht *serverHandlerTransport) runStream() {
376 for {
377 select {
378 case fn, ok := <-ht.writes:
379 if !ok {
380 return
381 }
382 fn()
383 case <-ht.closedCh:
384 return
385 }
386 }
387 }
388
389 func (ht *serverHandlerTransport) Drain() {
390 panic("Drain() is not implemented")
391 }
392
393 // mapRecvMsgError returns the non-nil err into the appropriate
394 // error value as expected by callers of *grpc.parser.recvMsg.
395 // In particular, in can only be:
396 // * io.EOF
397 // * io.ErrUnexpectedEOF
398 // * of type transport.ConnectionError
399 // * of type transport.StreamError
400 func mapRecvMsgError(err error) error {
401 if err == io.EOF || err == io.ErrUnexpectedEOF {
402 return err
403 }
404 if se, ok := err.(http2.StreamError); ok {
405 if code, ok := http2ErrConvTab[se.Code]; ok {
406 return StreamError{
407 Code: code,
408 Desc: se.Error(),
409 }
410 }
411 }
412 return connectionErrorf(true, err, err.Error())
413 }