http.go 8.8 KB

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