github.com/number571/tendermint@v0.34.11-gost/rpc/jsonrpc/server/http_server.go (about) 1 // Commons for HTTP handling 2 package server 3 4 import ( 5 "bufio" 6 "encoding/json" 7 "errors" 8 "fmt" 9 "net" 10 "net/http" 11 "os" 12 "runtime/debug" 13 "strings" 14 "time" 15 16 "golang.org/x/net/netutil" 17 18 "github.com/number571/tendermint/libs/log" 19 types "github.com/number571/tendermint/rpc/jsonrpc/types" 20 ) 21 22 // Config is a RPC server configuration. 23 type Config struct { 24 // see netutil.LimitListener 25 MaxOpenConnections int 26 // mirrors http.Server#ReadTimeout 27 ReadTimeout time.Duration 28 // mirrors http.Server#WriteTimeout 29 WriteTimeout time.Duration 30 // MaxBodyBytes controls the maximum number of bytes the 31 // server will read parsing the request body. 32 MaxBodyBytes int64 33 // mirrors http.Server#MaxHeaderBytes 34 MaxHeaderBytes int 35 } 36 37 // DefaultConfig returns a default configuration. 38 func DefaultConfig() *Config { 39 return &Config{ 40 MaxOpenConnections: 0, // unlimited 41 ReadTimeout: 10 * time.Second, 42 WriteTimeout: 10 * time.Second, 43 MaxBodyBytes: int64(1000000), // 1MB 44 MaxHeaderBytes: 1 << 20, // same as the net/http default 45 } 46 } 47 48 // Serve creates a http.Server and calls Serve with the given listener. It 49 // wraps handler with RecoverAndLogHandler and a handler, which limits the max 50 // body size to config.MaxBodyBytes. 51 // 52 // NOTE: This function blocks - you may want to call it in a go-routine. 53 func Serve(listener net.Listener, handler http.Handler, logger log.Logger, config *Config) error { 54 logger.Info(fmt.Sprintf("Starting RPC HTTP server on %s", listener.Addr())) 55 s := &http.Server{ 56 Handler: RecoverAndLogHandler(maxBytesHandler{h: handler, n: config.MaxBodyBytes}, logger), 57 ReadTimeout: config.ReadTimeout, 58 WriteTimeout: config.WriteTimeout, 59 MaxHeaderBytes: config.MaxHeaderBytes, 60 } 61 err := s.Serve(listener) 62 logger.Info("RPC HTTP server stopped", "err", err) 63 return err 64 } 65 66 // Serve creates a http.Server and calls ServeTLS with the given listener, 67 // certFile and keyFile. It wraps handler with RecoverAndLogHandler and a 68 // handler, which limits the max body size to config.MaxBodyBytes. 69 // 70 // NOTE: This function blocks - you may want to call it in a go-routine. 71 func ServeTLS( 72 listener net.Listener, 73 handler http.Handler, 74 certFile, keyFile string, 75 logger log.Logger, 76 config *Config, 77 ) error { 78 logger.Info(fmt.Sprintf("Starting RPC HTTPS server on %s (cert: %q, key: %q)", 79 listener.Addr(), certFile, keyFile)) 80 s := &http.Server{ 81 Handler: RecoverAndLogHandler(maxBytesHandler{h: handler, n: config.MaxBodyBytes}, logger), 82 ReadTimeout: config.ReadTimeout, 83 WriteTimeout: config.WriteTimeout, 84 MaxHeaderBytes: config.MaxHeaderBytes, 85 } 86 err := s.ServeTLS(listener, certFile, keyFile) 87 88 logger.Error("RPC HTTPS server stopped", "err", err) 89 return err 90 } 91 92 // WriteRPCResponseHTTPError marshals res as JSON (with indent) and writes it 93 // to w. 94 // 95 // Maps JSON RPC error codes to HTTP Status codes as follows: 96 // 97 // HTTP Status code message 98 // 500 -32700 Parse error. 99 // 400 -32600 Invalid Request. 100 // 404 -32601 Method not found. 101 // 500 -32602 Invalid params. 102 // 500 -32603 Internal error. 103 // 500 -32099..-32000 Server error. 104 // 105 // source: https://www.jsonrpc.org/historical/json-rpc-over-http.html 106 func WriteRPCResponseHTTPError( 107 w http.ResponseWriter, 108 res types.RPCResponse, 109 ) error { 110 if res.Error == nil { 111 panic("tried to write http error response without RPC error") 112 } 113 114 jsonBytes, err := json.MarshalIndent(res, "", " ") 115 if err != nil { 116 return fmt.Errorf("json marshal: %w", err) 117 } 118 119 var httpCode int 120 switch res.Error.Code { 121 case -32600: 122 httpCode = http.StatusBadRequest 123 case -32601: 124 httpCode = http.StatusNotFound 125 default: 126 httpCode = http.StatusInternalServerError 127 } 128 129 w.Header().Set("Content-Type", "application/json") 130 w.WriteHeader(httpCode) 131 _, err = w.Write(jsonBytes) 132 return err 133 } 134 135 // WriteRPCResponseHTTP marshals res as JSON (with indent) and writes it to w. 136 // If the rpc response can be cached, add cache-control to the response header. 137 func WriteRPCResponseHTTP(w http.ResponseWriter, c bool, res ...types.RPCResponse) error { 138 var v interface{} 139 if len(res) == 1 { 140 v = res[0] 141 } else { 142 v = res 143 } 144 145 jsonBytes, err := json.MarshalIndent(v, "", " ") 146 if err != nil { 147 return fmt.Errorf("json marshal: %w", err) 148 } 149 w.Header().Set("Content-Type", "application/json") 150 if c { 151 w.Header().Set("Cache-Control", "max-age=31536000") // expired after one year 152 } 153 w.WriteHeader(200) 154 _, err = w.Write(jsonBytes) 155 return err 156 } 157 158 //----------------------------------------------------------------------------- 159 160 // RecoverAndLogHandler wraps an HTTP handler, adding error logging. 161 // If the inner function panics, the outer function recovers, logs, sends an 162 // HTTP 500 error response. 163 func RecoverAndLogHandler(handler http.Handler, logger log.Logger) http.Handler { 164 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 165 // Wrap the ResponseWriter to remember the status 166 rww := &responseWriterWrapper{-1, w} 167 begin := time.Now() 168 169 rww.Header().Set("X-Server-Time", fmt.Sprintf("%v", begin.Unix())) 170 171 defer func() { 172 // Handle any panics in the panic handler below. Does not use the logger, since we want 173 // to avoid any further panics. However, we try to return a 500, since it otherwise 174 // defaults to 200 and there is no other way to terminate the connection. If that 175 // should panic for whatever reason then the Go HTTP server will handle it and 176 // terminate the connection - panicing is the de-facto and only way to get the Go HTTP 177 // server to terminate the request and close the connection/stream: 178 // https://github.com/golang/go/issues/17790#issuecomment-258481416 179 if e := recover(); e != nil { 180 fmt.Fprintf(os.Stderr, "Panic during RPC panic recovery: %v\n%v\n", e, string(debug.Stack())) 181 w.WriteHeader(500) 182 } 183 }() 184 185 defer func() { 186 // Send a 500 error if a panic happens during a handler. 187 // Without this, Chrome & Firefox were retrying aborted ajax requests, 188 // at least to my localhost. 189 if e := recover(); e != nil { 190 191 // If RPCResponse 192 if res, ok := e.(types.RPCResponse); ok { 193 if wErr := WriteRPCResponseHTTP(rww, false, res); wErr != nil { 194 logger.Error("failed to write response", "res", res, "err", wErr) 195 } 196 } else { 197 // Panics can contain anything, attempt to normalize it as an error. 198 var err error 199 switch e := e.(type) { 200 case error: 201 err = e 202 case string: 203 err = errors.New(e) 204 case fmt.Stringer: 205 err = errors.New(e.String()) 206 default: 207 } 208 209 logger.Error("panic in RPC HTTP handler", "err", e, "stack", string(debug.Stack())) 210 211 res := types.RPCInternalError(types.JSONRPCIntID(-1), err) 212 if wErr := WriteRPCResponseHTTPError(rww, res); wErr != nil { 213 logger.Error("failed to write response", "res", res, "err", wErr) 214 } 215 } 216 } 217 218 // Finally, log. 219 durationMS := time.Since(begin).Nanoseconds() / 1000000 220 if rww.Status == -1 { 221 rww.Status = 200 222 } 223 logger.Debug("served RPC HTTP response", 224 "method", r.Method, 225 "url", r.URL, 226 "status", rww.Status, 227 "duration", durationMS, 228 "remoteAddr", r.RemoteAddr, 229 ) 230 }() 231 232 handler.ServeHTTP(rww, r) 233 }) 234 } 235 236 // Remember the status for logging 237 type responseWriterWrapper struct { 238 Status int 239 http.ResponseWriter 240 } 241 242 func (w *responseWriterWrapper) WriteHeader(status int) { 243 w.Status = status 244 w.ResponseWriter.WriteHeader(status) 245 } 246 247 // implements http.Hijacker 248 func (w *responseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) { 249 return w.ResponseWriter.(http.Hijacker).Hijack() 250 } 251 252 type maxBytesHandler struct { 253 h http.Handler 254 n int64 255 } 256 257 func (h maxBytesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { 258 r.Body = http.MaxBytesReader(w, r.Body, h.n) 259 h.h.ServeHTTP(w, r) 260 } 261 262 // Listen starts a new net.Listener on the given address. 263 // It returns an error if the address is invalid or the call to Listen() fails. 264 func Listen(addr string, config *Config) (listener net.Listener, err error) { 265 parts := strings.SplitN(addr, "://", 2) 266 if len(parts) != 2 { 267 return nil, fmt.Errorf( 268 "invalid listening address %s (use fully formed addresses, including the tcp:// or unix:// prefix)", 269 addr, 270 ) 271 } 272 proto, addr := parts[0], parts[1] 273 listener, err = net.Listen(proto, addr) 274 if err != nil { 275 return nil, fmt.Errorf("failed to listen on %v: %v", addr, err) 276 } 277 if config.MaxOpenConnections > 0 { 278 listener = netutil.LimitListener(listener, config.MaxOpenConnections) 279 } 280 281 return listener, nil 282 }