http.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package rpc
  17. import (
  18. "bytes"
  19. "context"
  20. "encoding/json"
  21. "errors"
  22. "fmt"
  23. "io"
  24. "io/ioutil"
  25. "mime"
  26. "net/http"
  27. "sync"
  28. "time"
  29. )
  30. const (
  31. maxRequestContentLength = 1024 * 1024 * 5
  32. contentType = "application/json"
  33. )
  34. // https://www.jsonrpc.org/historical/json-rpc-over-http.html#id13
  35. var acceptedContentTypes = []string{contentType, "application/json-rpc", "application/jsonrequest"}
  36. type httpConn struct {
  37. client *http.Client
  38. req *http.Request
  39. closeOnce sync.Once
  40. closeCh chan interface{}
  41. }
  42. // httpConn is treated specially by Client.
  43. func (hc *httpConn) writeJSON(context.Context, interface{}) error {
  44. panic("writeJSON called on httpConn")
  45. }
  46. func (hc *httpConn) remoteAddr() string {
  47. return hc.req.URL.String()
  48. }
  49. func (hc *httpConn) readBatch() ([]*jsonrpcMessage, bool, error) {
  50. <-hc.closeCh
  51. return nil, false, io.EOF
  52. }
  53. func (hc *httpConn) close() {
  54. hc.closeOnce.Do(func() { close(hc.closeCh) })
  55. }
  56. func (hc *httpConn) closed() <-chan interface{} {
  57. return hc.closeCh
  58. }
  59. // HTTPTimeouts represents the configuration params for the HTTP RPC server.
  60. type HTTPTimeouts struct {
  61. // ReadTimeout is the maximum duration for reading the entire
  62. // request, including the body.
  63. //
  64. // Because ReadTimeout does not let Handlers make per-request
  65. // decisions on each request body's acceptable deadline or
  66. // upload rate, most users will prefer to use
  67. // ReadHeaderTimeout. It is valid to use them both.
  68. ReadTimeout time.Duration
  69. // WriteTimeout is the maximum duration before timing out
  70. // writes of the response. It is reset whenever a new
  71. // request's header is read. Like ReadTimeout, it does not
  72. // let Handlers make decisions on a per-request basis.
  73. WriteTimeout time.Duration
  74. // IdleTimeout is the maximum amount of time to wait for the
  75. // next request when keep-alives are enabled. If IdleTimeout
  76. // is zero, the value of ReadTimeout is used. If both are
  77. // zero, ReadHeaderTimeout is used.
  78. IdleTimeout time.Duration
  79. }
  80. // DefaultHTTPTimeouts represents the default timeout values used if further
  81. // configuration is not provided.
  82. var DefaultHTTPTimeouts = HTTPTimeouts{
  83. ReadTimeout: 30 * time.Second,
  84. WriteTimeout: 30 * time.Second,
  85. IdleTimeout: 120 * time.Second,
  86. }
  87. // DialHTTPWithClient creates a new RPC client that connects to an RPC server over HTTP
  88. // using the provided HTTP Client.
  89. func DialHTTPWithClient(endpoint string, client *http.Client) (*Client, error) {
  90. req, err := http.NewRequest(http.MethodPost, endpoint, nil)
  91. if err != nil {
  92. return nil, err
  93. }
  94. req.Header.Set("Content-Type", contentType)
  95. req.Header.Set("Accept", contentType)
  96. initctx := context.Background()
  97. return newClient(initctx, func(context.Context) (ServerCodec, error) {
  98. return &httpConn{client: client, req: req, closeCh: make(chan interface{})}, nil
  99. })
  100. }
  101. // DialHTTP creates a new RPC client that connects to an RPC server over HTTP.
  102. func DialHTTP(endpoint string) (*Client, error) {
  103. return DialHTTPWithClient(endpoint, new(http.Client))
  104. }
  105. func (c *Client) sendHTTP(ctx context.Context, op *requestOp, msg interface{}) error {
  106. hc := c.writeConn.(*httpConn)
  107. respBody, err := hc.doRequest(ctx, msg)
  108. if respBody != nil {
  109. defer respBody.Close()
  110. }
  111. if err != nil {
  112. if respBody != nil {
  113. buf := new(bytes.Buffer)
  114. if _, err2 := buf.ReadFrom(respBody); err2 == nil {
  115. return fmt.Errorf("%v %v", err, buf.String())
  116. }
  117. }
  118. return err
  119. }
  120. var respmsg jsonrpcMessage
  121. if err := json.NewDecoder(respBody).Decode(&respmsg); err != nil {
  122. return err
  123. }
  124. op.resp <- &respmsg
  125. return nil
  126. }
  127. func (c *Client) sendBatchHTTP(ctx context.Context, op *requestOp, msgs []*jsonrpcMessage) error {
  128. hc := c.writeConn.(*httpConn)
  129. respBody, err := hc.doRequest(ctx, msgs)
  130. if err != nil {
  131. return err
  132. }
  133. defer respBody.Close()
  134. var respmsgs []jsonrpcMessage
  135. if err := json.NewDecoder(respBody).Decode(&respmsgs); err != nil {
  136. return err
  137. }
  138. for i := 0; i < len(respmsgs); i++ {
  139. op.resp <- &respmsgs[i]
  140. }
  141. return nil
  142. }
  143. func (hc *httpConn) doRequest(ctx context.Context, msg interface{}) (io.ReadCloser, error) {
  144. body, err := json.Marshal(msg)
  145. if err != nil {
  146. return nil, err
  147. }
  148. req := hc.req.WithContext(ctx)
  149. req.Body = ioutil.NopCloser(bytes.NewReader(body))
  150. req.ContentLength = int64(len(body))
  151. resp, err := hc.client.Do(req)
  152. if err != nil {
  153. return nil, err
  154. }
  155. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  156. return resp.Body, errors.New(resp.Status)
  157. }
  158. return resp.Body, nil
  159. }
  160. // httpServerConn turns a HTTP connection into a Conn.
  161. type httpServerConn struct {
  162. io.Reader
  163. io.Writer
  164. r *http.Request
  165. }
  166. func newHTTPServerConn(r *http.Request, w http.ResponseWriter) ServerCodec {
  167. body := io.LimitReader(r.Body, maxRequestContentLength)
  168. conn := &httpServerConn{Reader: body, Writer: w, r: r}
  169. return NewCodec(conn)
  170. }
  171. // Close does nothing and always returns nil.
  172. func (t *httpServerConn) Close() error { return nil }
  173. // RemoteAddr returns the peer address of the underlying connection.
  174. func (t *httpServerConn) RemoteAddr() string {
  175. return t.r.RemoteAddr
  176. }
  177. // SetWriteDeadline does nothing and always returns nil.
  178. func (t *httpServerConn) SetWriteDeadline(time.Time) error { return nil }
  179. // ServeHTTP serves JSON-RPC requests over HTTP.
  180. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  181. // Permit dumb empty requests for remote health-checks (AWS)
  182. if r.Method == http.MethodGet && r.ContentLength == 0 && r.URL.RawQuery == "" {
  183. w.WriteHeader(http.StatusOK)
  184. return
  185. }
  186. if code, err := validateRequest(r); err != nil {
  187. http.Error(w, err.Error(), code)
  188. return
  189. }
  190. // All checks passed, create a codec that reads directly from the request body
  191. // until EOF, writes the response to w, and orders the server to process a
  192. // single request.
  193. ctx := r.Context()
  194. ctx = context.WithValue(ctx, "remote", r.RemoteAddr)
  195. ctx = context.WithValue(ctx, "scheme", r.Proto)
  196. ctx = context.WithValue(ctx, "local", r.Host)
  197. if ua := r.Header.Get("User-Agent"); ua != "" {
  198. ctx = context.WithValue(ctx, "User-Agent", ua)
  199. }
  200. if origin := r.Header.Get("Origin"); origin != "" {
  201. ctx = context.WithValue(ctx, "Origin", origin)
  202. }
  203. w.Header().Set("content-type", contentType)
  204. codec := newHTTPServerConn(r, w)
  205. defer codec.close()
  206. s.serveSingleRequest(ctx, codec)
  207. }
  208. // validateRequest returns a non-zero response code and error message if the
  209. // request is invalid.
  210. func validateRequest(r *http.Request) (int, error) {
  211. if r.Method == http.MethodPut || r.Method == http.MethodDelete {
  212. return http.StatusMethodNotAllowed, errors.New("method not allowed")
  213. }
  214. if r.ContentLength > maxRequestContentLength {
  215. err := fmt.Errorf("content length too large (%d>%d)", r.ContentLength, maxRequestContentLength)
  216. return http.StatusRequestEntityTooLarge, err
  217. }
  218. // Allow OPTIONS (regardless of content-type)
  219. if r.Method == http.MethodOptions {
  220. return 0, nil
  221. }
  222. // Check content-type
  223. if mt, _, err := mime.ParseMediaType(r.Header.Get("content-type")); err == nil {
  224. for _, accepted := range acceptedContentTypes {
  225. if accepted == mt {
  226. return 0, nil
  227. }
  228. }
  229. }
  230. // Invalid content-type
  231. err := fmt.Errorf("invalid content type, only %s is supported", contentType)
  232. return http.StatusUnsupportedMediaType, err
  233. }