http.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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"
  27. "net/http"
  28. "sync"
  29. "time"
  30. "github.com/rs/cors"
  31. )
  32. const (
  33. contentType = "application/json"
  34. maxHTTPRequestContentLength = 1024 * 128
  35. )
  36. var nullAddr, _ = net.ResolveTCPAddr("tcp", "127.0.0.1:0")
  37. type httpConn struct {
  38. client *http.Client
  39. req *http.Request
  40. closeOnce sync.Once
  41. closed chan struct{}
  42. }
  43. // httpConn is treated specially by Client.
  44. func (hc *httpConn) LocalAddr() net.Addr { return nullAddr }
  45. func (hc *httpConn) RemoteAddr() net.Addr { return nullAddr }
  46. func (hc *httpConn) SetReadDeadline(time.Time) error { return nil }
  47. func (hc *httpConn) SetWriteDeadline(time.Time) error { return nil }
  48. func (hc *httpConn) SetDeadline(time.Time) error { return nil }
  49. func (hc *httpConn) Write([]byte) (int, error) { panic("Write called") }
  50. func (hc *httpConn) Read(b []byte) (int, error) {
  51. <-hc.closed
  52. return 0, io.EOF
  53. }
  54. func (hc *httpConn) Close() error {
  55. hc.closeOnce.Do(func() { close(hc.closed) })
  56. return nil
  57. }
  58. // DialHTTP creates a new RPC clients that connection to an RPC server over HTTP.
  59. func DialHTTP(endpoint string) (*Client, error) {
  60. req, err := http.NewRequest(http.MethodPost, endpoint, nil)
  61. if err != nil {
  62. return nil, err
  63. }
  64. req.Header.Set("Content-Type", contentType)
  65. req.Header.Set("Accept", contentType)
  66. initctx := context.Background()
  67. return newClient(initctx, func(context.Context) (net.Conn, error) {
  68. return &httpConn{client: new(http.Client), req: req, closed: make(chan struct{})}, nil
  69. })
  70. }
  71. func (c *Client) sendHTTP(ctx context.Context, op *requestOp, msg interface{}) error {
  72. hc := c.writeConn.(*httpConn)
  73. respBody, err := hc.doRequest(ctx, msg)
  74. if err != nil {
  75. return err
  76. }
  77. defer respBody.Close()
  78. var respmsg jsonrpcMessage
  79. if err := json.NewDecoder(respBody).Decode(&respmsg); err != nil {
  80. return err
  81. }
  82. op.resp <- &respmsg
  83. return nil
  84. }
  85. func (c *Client) sendBatchHTTP(ctx context.Context, op *requestOp, msgs []*jsonrpcMessage) error {
  86. hc := c.writeConn.(*httpConn)
  87. respBody, err := hc.doRequest(ctx, msgs)
  88. if err != nil {
  89. return err
  90. }
  91. defer respBody.Close()
  92. var respmsgs []jsonrpcMessage
  93. if err := json.NewDecoder(respBody).Decode(&respmsgs); err != nil {
  94. return err
  95. }
  96. for i := 0; i < len(respmsgs); i++ {
  97. op.resp <- &respmsgs[i]
  98. }
  99. return nil
  100. }
  101. func (hc *httpConn) doRequest(ctx context.Context, msg interface{}) (io.ReadCloser, error) {
  102. body, err := json.Marshal(msg)
  103. if err != nil {
  104. return nil, err
  105. }
  106. req := hc.req.WithContext(ctx)
  107. req.Body = ioutil.NopCloser(bytes.NewReader(body))
  108. req.ContentLength = int64(len(body))
  109. resp, err := hc.client.Do(req)
  110. if err != nil {
  111. return nil, err
  112. }
  113. return resp.Body, nil
  114. }
  115. // httpReadWriteNopCloser wraps a io.Reader and io.Writer with a NOP Close method.
  116. type httpReadWriteNopCloser struct {
  117. io.Reader
  118. io.Writer
  119. }
  120. // Close does nothing and returns always nil
  121. func (t *httpReadWriteNopCloser) Close() error {
  122. return nil
  123. }
  124. // NewHTTPServer creates a new HTTP RPC server around an API provider.
  125. //
  126. // Deprecated: Server implements http.Handler
  127. func NewHTTPServer(cors []string, srv *Server) *http.Server {
  128. return &http.Server{Handler: newCorsHandler(srv, cors)}
  129. }
  130. // ServeHTTP serves JSON-RPC requests over HTTP.
  131. func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  132. // Permit dumb empty requests for remote health-checks (AWS)
  133. if r.Method == http.MethodGet && r.ContentLength == 0 && r.URL.RawQuery == "" {
  134. return
  135. }
  136. if code, err := validateRequest(r); err != nil {
  137. http.Error(w, err.Error(), code)
  138. return
  139. }
  140. // All checks passed, create a codec that reads direct from the request body
  141. // untilEOF and writes the response to w and order the server to process a
  142. // single request.
  143. codec := NewJSONCodec(&httpReadWriteNopCloser{r.Body, w})
  144. defer codec.Close()
  145. w.Header().Set("content-type", contentType)
  146. srv.ServeSingleRequest(codec, OptionMethodInvocation)
  147. }
  148. // validateRequest returns a non-zero response code and error message if the
  149. // request is invalid.
  150. func validateRequest(r *http.Request) (int, error) {
  151. if r.Method == http.MethodPut || r.Method == http.MethodDelete {
  152. return http.StatusMethodNotAllowed, errors.New("method not allowed")
  153. }
  154. if r.ContentLength > maxHTTPRequestContentLength {
  155. err := fmt.Errorf("content length too large (%d>%d)", r.ContentLength, maxHTTPRequestContentLength)
  156. return http.StatusRequestEntityTooLarge, err
  157. }
  158. mt, _, err := mime.ParseMediaType(r.Header.Get("content-type"))
  159. if r.Method != http.MethodOptions && (err != nil || mt != contentType) {
  160. err := fmt.Errorf("invalid content type, only %s is supported", contentType)
  161. return http.StatusUnsupportedMediaType, err
  162. }
  163. return 0, nil
  164. }
  165. func newCorsHandler(srv *Server, allowedOrigins []string) http.Handler {
  166. // disable CORS support if user has not specified a custom CORS configuration
  167. if len(allowedOrigins) == 0 {
  168. return srv
  169. }
  170. c := cors.New(cors.Options{
  171. AllowedOrigins: allowedOrigins,
  172. AllowedMethods: []string{http.MethodPost, http.MethodGet},
  173. MaxAge: 600,
  174. AllowedHeaders: []string{"*"},
  175. })
  176. return c.Handler(srv)
  177. }