handler_server.go 12 KB

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