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