handler_server.go 14 KB

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