http.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. "net/url"
  28. "sync"
  29. "time"
  30. )
  31. const (
  32. maxRequestContentLength = 1024 * 1024 * 5
  33. contentType = "application/json"
  34. )
  35. // https://www.jsonrpc.org/historical/json-rpc-over-http.html#id13
  36. var acceptedContentTypes = []string{contentType, "application/json-rpc", "application/jsonrequest"}
  37. type httpConn struct {
  38. client *http.Client
  39. url string
  40. closeOnce sync.Once
  41. closeCh chan interface{}
  42. mu sync.Mutex // protects headers
  43. headers http.Header
  44. }
  45. // httpConn is treated specially by Client.
  46. func (hc *httpConn) writeJSON(context.Context, interface{}) error {
  47. panic("writeJSON called on httpConn")
  48. }
  49. func (hc *httpConn) remoteAddr() string {
  50. return hc.url
  51. }
  52. func (hc *httpConn) readBatch() ([]*jsonrpcMessage, bool, error) {
  53. <-hc.closeCh
  54. return nil, false, io.EOF
  55. }
  56. func (hc *httpConn) close() {
  57. hc.closeOnce.Do(func() { close(hc.closeCh) })
  58. }
  59. func (hc *httpConn) closed() <-chan interface{} {
  60. return hc.closeCh
  61. }
  62. // HTTPTimeouts represents the configuration params for the HTTP RPC server.
  63. type HTTPTimeouts struct {
  64. // ReadTimeout is the maximum duration for reading the entire
  65. // request, including the body.
  66. //
  67. // Because ReadTimeout does not let Handlers make per-request
  68. // decisions on each request body's acceptable deadline or
  69. // upload rate, most users will prefer to use
  70. // ReadHeaderTimeout. It is valid to use them both.
  71. ReadTimeout time.Duration
  72. // WriteTimeout is the maximum duration before timing out
  73. // writes of the response. It is reset whenever a new
  74. // request's header is read. Like ReadTimeout, it does not
  75. // let Handlers make decisions on a per-request basis.
  76. WriteTimeout time.Duration
  77. // IdleTimeout is the maximum amount of time to wait for the
  78. // next request when keep-alives are enabled. If IdleTimeout
  79. // is zero, the value of ReadTimeout is used. If both are
  80. // zero, ReadHeaderTimeout is used.
  81. IdleTimeout time.Duration
  82. }
  83. // DefaultHTTPTimeouts represents the default timeout values used if further
  84. // configuration is not provided.
  85. var DefaultHTTPTimeouts = HTTPTimeouts{
  86. ReadTimeout: 30 * time.Second,
  87. WriteTimeout: 30 * time.Second,
  88. IdleTimeout: 120 * time.Second,
  89. }
  90. // DialHTTPWithClient creates a new RPC client that connects to an RPC server over HTTP
  91. // using the provided HTTP Client.
  92. func DialHTTPWithClient(endpoint string, client *http.Client) (*Client, error) {
  93. // Sanity check URL so we don't end up with a client that will fail every request.
  94. _, err := url.Parse(endpoint)
  95. if err != nil {
  96. return nil, err
  97. }
  98. initctx := context.Background()
  99. headers := make(http.Header, 2)
  100. headers.Set("accept", contentType)
  101. headers.Set("content-type", contentType)
  102. return newClient(initctx, func(context.Context) (ServerCodec, error) {
  103. hc := &httpConn{
  104. client: client,
  105. headers: headers,
  106. url: endpoint,
  107. closeCh: make(chan interface{}),
  108. }
  109. return hc, nil
  110. })
  111. }
  112. // DialHTTP creates a new RPC client that connects to an RPC server over HTTP.
  113. func DialHTTP(endpoint string) (*Client, error) {
  114. return DialHTTPWithClient(endpoint, new(http.Client))
  115. }
  116. func (c *Client) sendHTTP(ctx context.Context, op *requestOp, msg interface{}) error {
  117. hc := c.writeConn.(*httpConn)
  118. respBody, err := hc.doRequest(ctx, msg)
  119. if respBody != nil {
  120. defer respBody.Close()
  121. }
  122. if err != nil {
  123. if respBody != nil {
  124. buf := new(bytes.Buffer)
  125. if _, err2 := buf.ReadFrom(respBody); err2 == nil {
  126. return fmt.Errorf("%v: %v", err, buf.String())
  127. }
  128. }
  129. return err
  130. }
  131. var respmsg jsonrpcMessage
  132. if err := json.NewDecoder(respBody).Decode(&respmsg); err != nil {
  133. return err
  134. }
  135. op.resp <- &respmsg
  136. return nil
  137. }
  138. func (c *Client) sendBatchHTTP(ctx context.Context, op *requestOp, msgs []*jsonrpcMessage) error {
  139. hc := c.writeConn.(*httpConn)
  140. respBody, err := hc.doRequest(ctx, msgs)
  141. if err != nil {
  142. return err
  143. }
  144. defer respBody.Close()
  145. var respmsgs []jsonrpcMessage
  146. if err := json.NewDecoder(respBody).Decode(&respmsgs); err != nil {
  147. return err
  148. }
  149. for i := 0; i < len(respmsgs); i++ {
  150. op.resp <- &respmsgs[i]
  151. }
  152. return nil
  153. }
  154. func (hc *httpConn) doRequest(ctx context.Context, msg interface{}) (io.ReadCloser, error) {
  155. body, err := json.Marshal(msg)
  156. if err != nil {
  157. return nil, err
  158. }
  159. req, err := http.NewRequestWithContext(ctx, "POST", hc.url, ioutil.NopCloser(bytes.NewReader(body)))
  160. if err != nil {
  161. return nil, err
  162. }
  163. req.ContentLength = int64(len(body))
  164. // set headers
  165. hc.mu.Lock()
  166. req.Header = hc.headers.Clone()
  167. hc.mu.Unlock()
  168. // do request
  169. resp, err := hc.client.Do(req)
  170. if err != nil {
  171. return nil, err
  172. }
  173. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  174. return resp.Body, errors.New(resp.Status)
  175. }
  176. return resp.Body, nil
  177. }
  178. // httpServerConn turns a HTTP connection into a Conn.
  179. type httpServerConn struct {
  180. io.Reader
  181. io.Writer
  182. r *http.Request
  183. }
  184. func newHTTPServerConn(r *http.Request, w http.ResponseWriter) ServerCodec {
  185. body := io.LimitReader(r.Body, maxRequestContentLength)
  186. conn := &httpServerConn{Reader: body, Writer: w, r: r}
  187. return NewCodec(conn)
  188. }
  189. // Close does nothing and always returns nil.
  190. func (t *httpServerConn) Close() error { return nil }
  191. // RemoteAddr returns the peer address of the underlying connection.
  192. func (t *httpServerConn) RemoteAddr() string {
  193. return t.r.RemoteAddr
  194. }
  195. // SetWriteDeadline does nothing and always returns nil.
  196. func (t *httpServerConn) SetWriteDeadline(time.Time) error { return nil }
  197. // ServeHTTP serves JSON-RPC requests over HTTP.
  198. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  199. // Permit dumb empty requests for remote health-checks (AWS)
  200. if r.Method == http.MethodGet && r.ContentLength == 0 && r.URL.RawQuery == "" {
  201. w.WriteHeader(http.StatusOK)
  202. return
  203. }
  204. if code, err := validateRequest(r); err != nil {
  205. http.Error(w, err.Error(), code)
  206. return
  207. }
  208. // All checks passed, create a codec that reads directly from the request body
  209. // until EOF, writes the response to w, and orders the server to process a
  210. // single request.
  211. ctx := r.Context()
  212. ctx = context.WithValue(ctx, "remote", r.RemoteAddr)
  213. ctx = context.WithValue(ctx, "scheme", r.Proto)
  214. ctx = context.WithValue(ctx, "local", r.Host)
  215. if ua := r.Header.Get("User-Agent"); ua != "" {
  216. ctx = context.WithValue(ctx, "User-Agent", ua)
  217. }
  218. if origin := r.Header.Get("Origin"); origin != "" {
  219. ctx = context.WithValue(ctx, "Origin", origin)
  220. }
  221. w.Header().Set("content-type", contentType)
  222. codec := newHTTPServerConn(r, w)
  223. defer codec.close()
  224. s.serveSingleRequest(ctx, codec)
  225. }
  226. // validateRequest returns a non-zero response code and error message if the
  227. // request is invalid.
  228. func validateRequest(r *http.Request) (int, error) {
  229. if r.Method == http.MethodPut || r.Method == http.MethodDelete {
  230. return http.StatusMethodNotAllowed, errors.New("method not allowed")
  231. }
  232. if r.ContentLength > maxRequestContentLength {
  233. err := fmt.Errorf("content length too large (%d>%d)", r.ContentLength, maxRequestContentLength)
  234. return http.StatusRequestEntityTooLarge, err
  235. }
  236. // Allow OPTIONS (regardless of content-type)
  237. if r.Method == http.MethodOptions {
  238. return 0, nil
  239. }
  240. // Check content-type
  241. if mt, _, err := mime.ParseMediaType(r.Header.Get("content-type")); err == nil {
  242. for _, accepted := range acceptedContentTypes {
  243. if accepted == mt {
  244. return 0, nil
  245. }
  246. }
  247. }
  248. // Invalid content-type
  249. err := fmt.Errorf("invalid content type, only %s is supported", contentType)
  250. return http.StatusUnsupportedMediaType, err
  251. }