http.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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 err != nil {
  120. return err
  121. }
  122. defer respBody.Close()
  123. var respmsg jsonrpcMessage
  124. if err := json.NewDecoder(respBody).Decode(&respmsg); err != nil {
  125. return err
  126. }
  127. op.resp <- &respmsg
  128. return nil
  129. }
  130. func (c *Client) sendBatchHTTP(ctx context.Context, op *requestOp, msgs []*jsonrpcMessage) error {
  131. hc := c.writeConn.(*httpConn)
  132. respBody, err := hc.doRequest(ctx, msgs)
  133. if err != nil {
  134. return err
  135. }
  136. defer respBody.Close()
  137. var respmsgs []jsonrpcMessage
  138. if err := json.NewDecoder(respBody).Decode(&respmsgs); err != nil {
  139. return err
  140. }
  141. for i := 0; i < len(respmsgs); i++ {
  142. op.resp <- &respmsgs[i]
  143. }
  144. return nil
  145. }
  146. func (hc *httpConn) doRequest(ctx context.Context, msg interface{}) (io.ReadCloser, error) {
  147. body, err := json.Marshal(msg)
  148. if err != nil {
  149. return nil, err
  150. }
  151. req, err := http.NewRequestWithContext(ctx, "POST", hc.url, ioutil.NopCloser(bytes.NewReader(body)))
  152. if err != nil {
  153. return nil, err
  154. }
  155. req.ContentLength = int64(len(body))
  156. // set headers
  157. hc.mu.Lock()
  158. req.Header = hc.headers.Clone()
  159. hc.mu.Unlock()
  160. // do request
  161. resp, err := hc.client.Do(req)
  162. if err != nil {
  163. return nil, err
  164. }
  165. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  166. var buf bytes.Buffer
  167. var body []byte
  168. if _, err := buf.ReadFrom(resp.Body); err == nil {
  169. body = buf.Bytes()
  170. }
  171. return nil, HTTPError{
  172. Status: resp.Status,
  173. StatusCode: resp.StatusCode,
  174. Body: body,
  175. }
  176. }
  177. return resp.Body, nil
  178. }
  179. // httpServerConn turns a HTTP connection into a Conn.
  180. type httpServerConn struct {
  181. io.Reader
  182. io.Writer
  183. r *http.Request
  184. }
  185. func newHTTPServerConn(r *http.Request, w http.ResponseWriter) ServerCodec {
  186. body := io.LimitReader(r.Body, maxRequestContentLength)
  187. conn := &httpServerConn{Reader: body, Writer: w, r: r}
  188. return NewCodec(conn)
  189. }
  190. // Close does nothing and always returns nil.
  191. func (t *httpServerConn) Close() error { return nil }
  192. // RemoteAddr returns the peer address of the underlying connection.
  193. func (t *httpServerConn) RemoteAddr() string {
  194. return t.r.RemoteAddr
  195. }
  196. // SetWriteDeadline does nothing and always returns nil.
  197. func (t *httpServerConn) SetWriteDeadline(time.Time) error { return nil }
  198. // ServeHTTP serves JSON-RPC requests over HTTP.
  199. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  200. // Permit dumb empty requests for remote health-checks (AWS)
  201. if r.Method == http.MethodGet && r.ContentLength == 0 && r.URL.RawQuery == "" {
  202. w.WriteHeader(http.StatusOK)
  203. return
  204. }
  205. if code, err := validateRequest(r); err != nil {
  206. http.Error(w, err.Error(), code)
  207. return
  208. }
  209. // All checks passed, create a codec that reads directly from the request body
  210. // until EOF, writes the response to w, and orders the server to process a
  211. // single request.
  212. ctx := r.Context()
  213. ctx = context.WithValue(ctx, "remote", r.RemoteAddr)
  214. ctx = context.WithValue(ctx, "scheme", r.Proto)
  215. ctx = context.WithValue(ctx, "local", r.Host)
  216. if ua := r.Header.Get("User-Agent"); ua != "" {
  217. ctx = context.WithValue(ctx, "User-Agent", ua)
  218. }
  219. if origin := r.Header.Get("Origin"); origin != "" {
  220. ctx = context.WithValue(ctx, "Origin", origin)
  221. }
  222. if xForward := r.Header.Get("X-Forwarded-For"); xForward != "" {
  223. ctx = context.WithValue(ctx, "X-Forwarded-For", xForward)
  224. }
  225. w.Header().Set("content-type", contentType)
  226. codec := newHTTPServerConn(r, w)
  227. defer codec.close()
  228. s.serveSingleRequest(ctx, codec)
  229. }
  230. // validateRequest returns a non-zero response code and error message if the
  231. // request is invalid.
  232. func validateRequest(r *http.Request) (int, error) {
  233. if r.Method == http.MethodPut || r.Method == http.MethodDelete {
  234. return http.StatusMethodNotAllowed, errors.New("method not allowed")
  235. }
  236. if r.ContentLength > maxRequestContentLength {
  237. err := fmt.Errorf("content length too large (%d>%d)", r.ContentLength, maxRequestContentLength)
  238. return http.StatusRequestEntityTooLarge, err
  239. }
  240. // Allow OPTIONS (regardless of content-type)
  241. if r.Method == http.MethodOptions {
  242. return 0, nil
  243. }
  244. // Check content-type
  245. if mt, _, err := mime.ParseMediaType(r.Header.Get("content-type")); err == nil {
  246. for _, accepted := range acceptedContentTypes {
  247. if accepted == mt {
  248. return 0, nil
  249. }
  250. }
  251. }
  252. // Invalid content-type
  253. err := fmt.Errorf("invalid content type, only %s is supported", contentType)
  254. return http.StatusUnsupportedMediaType, err
  255. }