handler_server.go 14 KB

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