server.go 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985
  1. package fasthttp
  2. import (
  3. "bufio"
  4. "context"
  5. "crypto/tls"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "log"
  10. "mime/multipart"
  11. "net"
  12. "os"
  13. "strings"
  14. "sync"
  15. "sync/atomic"
  16. "time"
  17. )
  18. var errNoCertOrKeyProvided = errors.New("cert or key has not provided")
  19. // ErrAlreadyServing is deprecated.
  20. // Deprecated: ErrAlreadyServing is never returned from Serve. See issue #633.
  21. var ErrAlreadyServing = errors.New("Server is already serving connections")
  22. // ServeConn serves HTTP requests from the given connection
  23. // using the given handler.
  24. //
  25. // ServeConn returns nil if all requests from the c are successfully served.
  26. // It returns non-nil error otherwise.
  27. //
  28. // Connection c must immediately propagate all the data passed to Write()
  29. // to the client. Otherwise requests' processing may hang.
  30. //
  31. // ServeConn closes c before returning.
  32. func ServeConn(c net.Conn, handler RequestHandler) error {
  33. v := serverPool.Get()
  34. if v == nil {
  35. v = &Server{}
  36. }
  37. s := v.(*Server)
  38. s.Handler = handler
  39. err := s.ServeConn(c)
  40. s.Handler = nil
  41. serverPool.Put(v)
  42. return err
  43. }
  44. var serverPool sync.Pool
  45. // Serve serves incoming connections from the given listener
  46. // using the given handler.
  47. //
  48. // Serve blocks until the given listener returns permanent error.
  49. func Serve(ln net.Listener, handler RequestHandler) error {
  50. s := &Server{
  51. Handler: handler,
  52. }
  53. return s.Serve(ln)
  54. }
  55. // ServeTLS serves HTTPS requests from the given net.Listener
  56. // using the given handler.
  57. //
  58. // certFile and keyFile are paths to TLS certificate and key files.
  59. func ServeTLS(ln net.Listener, certFile, keyFile string, handler RequestHandler) error {
  60. s := &Server{
  61. Handler: handler,
  62. }
  63. return s.ServeTLS(ln, certFile, keyFile)
  64. }
  65. // ServeTLSEmbed serves HTTPS requests from the given net.Listener
  66. // using the given handler.
  67. //
  68. // certData and keyData must contain valid TLS certificate and key data.
  69. func ServeTLSEmbed(ln net.Listener, certData, keyData []byte, handler RequestHandler) error {
  70. s := &Server{
  71. Handler: handler,
  72. }
  73. return s.ServeTLSEmbed(ln, certData, keyData)
  74. }
  75. // ListenAndServe serves HTTP requests from the given TCP addr
  76. // using the given handler.
  77. func ListenAndServe(addr string, handler RequestHandler) error {
  78. s := &Server{
  79. Handler: handler,
  80. }
  81. return s.ListenAndServe(addr)
  82. }
  83. // ListenAndServeUNIX serves HTTP requests from the given UNIX addr
  84. // using the given handler.
  85. //
  86. // The function deletes existing file at addr before starting serving.
  87. //
  88. // The server sets the given file mode for the UNIX addr.
  89. func ListenAndServeUNIX(addr string, mode os.FileMode, handler RequestHandler) error {
  90. s := &Server{
  91. Handler: handler,
  92. }
  93. return s.ListenAndServeUNIX(addr, mode)
  94. }
  95. // ListenAndServeTLS serves HTTPS requests from the given TCP addr
  96. // using the given handler.
  97. //
  98. // certFile and keyFile are paths to TLS certificate and key files.
  99. func ListenAndServeTLS(addr, certFile, keyFile string, handler RequestHandler) error {
  100. s := &Server{
  101. Handler: handler,
  102. }
  103. return s.ListenAndServeTLS(addr, certFile, keyFile)
  104. }
  105. // ListenAndServeTLSEmbed serves HTTPS requests from the given TCP addr
  106. // using the given handler.
  107. //
  108. // certData and keyData must contain valid TLS certificate and key data.
  109. func ListenAndServeTLSEmbed(addr string, certData, keyData []byte, handler RequestHandler) error {
  110. s := &Server{
  111. Handler: handler,
  112. }
  113. return s.ListenAndServeTLSEmbed(addr, certData, keyData)
  114. }
  115. // RequestHandler must process incoming requests.
  116. //
  117. // RequestHandler must call ctx.TimeoutError() before returning
  118. // if it keeps references to ctx and/or its members after the return.
  119. // Consider wrapping RequestHandler into TimeoutHandler if response time
  120. // must be limited.
  121. type RequestHandler func(ctx *RequestCtx)
  122. // ServeHandler must process tls.Config.NextProto negotiated requests.
  123. type ServeHandler func(c net.Conn) error
  124. // Server implements HTTP server.
  125. //
  126. // Default Server settings should satisfy the majority of Server users.
  127. // Adjust Server settings only if you really understand the consequences.
  128. //
  129. // It is forbidden copying Server instances. Create new Server instances
  130. // instead.
  131. //
  132. // It is safe to call Server methods from concurrently running goroutines.
  133. type Server struct {
  134. noCopy noCopy
  135. perIPConnCounter perIPConnCounter
  136. ctxPool sync.Pool
  137. readerPool sync.Pool
  138. writerPool sync.Pool
  139. hijackConnPool sync.Pool
  140. // Logger, which is used by RequestCtx.Logger().
  141. //
  142. // By default standard logger from log package is used.
  143. Logger Logger
  144. // Handler for processing incoming requests.
  145. //
  146. // Take into account that no `panic` recovery is done by `fasthttp` (thus any `panic` will take down the entire server).
  147. // Instead the user should use `recover` to handle these situations.
  148. Handler RequestHandler
  149. // ErrorHandler for returning a response in case of an error while receiving or parsing the request.
  150. //
  151. // The following is a non-exhaustive list of errors that can be expected as argument:
  152. // * io.EOF
  153. // * io.ErrUnexpectedEOF
  154. // * ErrGetOnly
  155. // * ErrSmallBuffer
  156. // * ErrBodyTooLarge
  157. // * ErrBrokenChunks
  158. ErrorHandler func(ctx *RequestCtx, err error)
  159. // HeaderReceived is called after receiving the header.
  160. //
  161. // Non zero RequestConfig field values will overwrite the default configs
  162. HeaderReceived func(header *RequestHeader) RequestConfig
  163. // ContinueHandler is called after receiving the Expect 100 Continue Header.
  164. //
  165. // https://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3
  166. // https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.1.1
  167. // Using ContinueHandler a server can make decisioning on whether or not
  168. // to read a potentially large request body based on the headers.
  169. //
  170. // The default is to automatically read request bodies of Expect 100 Continue requests
  171. // like they are normal requests.
  172. ContinueHandler func(header *RequestHeader) bool
  173. // ConnState specifies an optional callback function that is
  174. // called when a client connection changes state. See the
  175. // ConnState type and associated constants for details.
  176. ConnState func(net.Conn, ConnState)
  177. // TLSConfig optionally provides a TLS configuration for use
  178. // by ServeTLS, ServeTLSEmbed, ListenAndServeTLS, ListenAndServeTLSEmbed,
  179. // AppendCert, AppendCertEmbed and NextProto.
  180. //
  181. // Note that this value is cloned by ServeTLS, ServeTLSEmbed, ListenAndServeTLS
  182. // and ListenAndServeTLSEmbed, so it's not possible to modify the configuration
  183. // with methods like tls.Config.SetSessionTicketKeys.
  184. // To use SetSessionTicketKeys, use Server.Serve with a TLS Listener
  185. // instead.
  186. TLSConfig *tls.Config
  187. // FormValueFunc, which is used by RequestCtx.FormValue and support for customizing
  188. // the behaviour of the RequestCtx.FormValue function.
  189. //
  190. // NetHttpFormValueFunc gives a FormValueFunc func implementation that is consistent with net/http.
  191. FormValueFunc FormValueFunc
  192. nextProtos map[string]ServeHandler
  193. concurrencyCh chan struct{}
  194. idleConns map[net.Conn]time.Time
  195. done chan struct{}
  196. // Server name for sending in response headers.
  197. //
  198. // Default server name is used if left blank.
  199. Name string
  200. // We need to know our listeners and idle connections so we can close them in Shutdown().
  201. ln []net.Listener
  202. // The maximum number of concurrent connections the server may serve.
  203. //
  204. // DefaultConcurrency is used if not set.
  205. //
  206. // Concurrency only works if you either call Serve once, or only ServeConn multiple times.
  207. // It works with ListenAndServe as well.
  208. Concurrency int
  209. // Per-connection buffer size for requests' reading.
  210. // This also limits the maximum header size.
  211. //
  212. // Increase this buffer if your clients send multi-KB RequestURIs
  213. // and/or multi-KB headers (for example, BIG cookies).
  214. //
  215. // Default buffer size is used if not set.
  216. ReadBufferSize int
  217. // Per-connection buffer size for responses' writing.
  218. //
  219. // Default buffer size is used if not set.
  220. WriteBufferSize int
  221. // ReadTimeout is the amount of time allowed to read
  222. // the full request including body. The connection's read
  223. // deadline is reset when the connection opens, or for
  224. // keep-alive connections after the first byte has been read.
  225. //
  226. // By default request read timeout is unlimited.
  227. ReadTimeout time.Duration
  228. // WriteTimeout is the maximum duration before timing out
  229. // writes of the response. It is reset after the request handler
  230. // has returned.
  231. //
  232. // By default response write timeout is unlimited.
  233. WriteTimeout time.Duration
  234. // IdleTimeout is the maximum amount of time to wait for the
  235. // next request when keep-alive is enabled. If IdleTimeout
  236. // is zero, the value of ReadTimeout is used.
  237. IdleTimeout time.Duration
  238. // Maximum number of concurrent client connections allowed per IP.
  239. //
  240. // By default unlimited number of concurrent connections
  241. // may be established to the server from a single IP address.
  242. MaxConnsPerIP int
  243. // Maximum number of requests served per connection.
  244. //
  245. // The server closes connection after the last request.
  246. // 'Connection: close' header is added to the last response.
  247. //
  248. // By default unlimited number of requests may be served per connection.
  249. MaxRequestsPerConn int
  250. // MaxKeepaliveDuration is a no-op and only left here for backwards compatibility.
  251. // Deprecated: Use IdleTimeout instead.
  252. MaxKeepaliveDuration time.Duration
  253. // MaxIdleWorkerDuration is the maximum idle time of a single worker in the underlying
  254. // worker pool of the Server. Idle workers beyond this time will be cleared.
  255. MaxIdleWorkerDuration time.Duration
  256. // Period between tcp keep-alive messages.
  257. //
  258. // TCP keep-alive period is determined by operation system by default.
  259. TCPKeepalivePeriod time.Duration
  260. // Maximum request body size.
  261. //
  262. // The server rejects requests with bodies exceeding this limit.
  263. //
  264. // Request body size is limited by DefaultMaxRequestBodySize by default.
  265. MaxRequestBodySize int
  266. // SleepWhenConcurrencyLimitsExceeded is a duration to be slept of if
  267. // the concurrency limit in exceeded (default [when is 0]: don't sleep
  268. // and accept new connections immediately).
  269. SleepWhenConcurrencyLimitsExceeded time.Duration
  270. idleConnsMu sync.Mutex
  271. mu sync.Mutex
  272. concurrency uint32
  273. open int32
  274. stop int32
  275. rejectedRequestsCount uint32
  276. // Whether to disable keep-alive connections.
  277. //
  278. // The server will close all the incoming connections after sending
  279. // the first response to client if this option is set to true.
  280. //
  281. // By default keep-alive connections are enabled.
  282. DisableKeepalive bool
  283. // Whether to enable tcp keep-alive connections.
  284. //
  285. // Whether the operating system should send tcp keep-alive messages on the tcp connection.
  286. //
  287. // By default tcp keep-alive connections are disabled.
  288. TCPKeepalive bool
  289. // Aggressively reduces memory usage at the cost of higher CPU usage
  290. // if set to true.
  291. //
  292. // Try enabling this option only if the server consumes too much memory
  293. // serving mostly idle keep-alive connections. This may reduce memory
  294. // usage by more than 50%.
  295. //
  296. // Aggressive memory usage reduction is disabled by default.
  297. ReduceMemoryUsage bool
  298. // Rejects all non-GET requests if set to true.
  299. //
  300. // This option is useful as anti-DoS protection for servers
  301. // accepting only GET requests and HEAD requests. The request size is limited
  302. // by ReadBufferSize if GetOnly is set.
  303. //
  304. // Server accepts all the requests by default.
  305. GetOnly bool
  306. // Will not pre parse Multipart Form data if set to true.
  307. //
  308. // This option is useful for servers that desire to treat
  309. // multipart form data as a binary blob, or choose when to parse the data.
  310. //
  311. // Server pre parses multipart form data by default.
  312. DisablePreParseMultipartForm bool
  313. // Logs all errors, including the most frequent
  314. // 'connection reset by peer', 'broken pipe' and 'connection timeout'
  315. // errors. Such errors are common in production serving real-world
  316. // clients.
  317. //
  318. // By default the most frequent errors such as
  319. // 'connection reset by peer', 'broken pipe' and 'connection timeout'
  320. // are suppressed in order to limit output log traffic.
  321. LogAllErrors bool
  322. // Will not log potentially sensitive content in error logs
  323. //
  324. // This option is useful for servers that handle sensitive data
  325. // in the request/response.
  326. //
  327. // Server logs all full errors by default.
  328. SecureErrorLogMessage bool
  329. // Header names are passed as-is without normalization
  330. // if this option is set.
  331. //
  332. // Disabled header names' normalization may be useful only for proxying
  333. // incoming requests to other servers expecting case-sensitive
  334. // header names. See https://github.com/valyala/fasthttp/issues/57
  335. // for details.
  336. //
  337. // By default request and response header names are normalized, i.e.
  338. // The first letter and the first letters following dashes
  339. // are uppercased, while all the other letters are lowercased.
  340. // Examples:
  341. //
  342. // * HOST -> Host
  343. // * content-type -> Content-Type
  344. // * cONTENT-lenGTH -> Content-Length
  345. DisableHeaderNamesNormalizing bool
  346. // NoDefaultServerHeader, when set to true, causes the default Server header
  347. // to be excluded from the Response.
  348. //
  349. // The default Server header value is the value of the Name field or an
  350. // internal default value in its absence. With this option set to true,
  351. // the only time a Server header will be sent is if a non-zero length
  352. // value is explicitly provided during a request.
  353. NoDefaultServerHeader bool
  354. // NoDefaultDate, when set to true, causes the default Date
  355. // header to be excluded from the Response.
  356. //
  357. // The default Date header value is the current date value. When
  358. // set to true, the Date will not be present.
  359. NoDefaultDate bool
  360. // NoDefaultContentType, when set to true, causes the default Content-Type
  361. // header to be excluded from the Response.
  362. //
  363. // The default Content-Type header value is the internal default value. When
  364. // set to true, the Content-Type will not be present.
  365. NoDefaultContentType bool
  366. // KeepHijackedConns is an opt-in disable of connection
  367. // close by fasthttp after connections' HijackHandler returns.
  368. // This allows to save goroutines, e.g. when fasthttp used to upgrade
  369. // http connections to WS and connection goes to another handler,
  370. // which will close it when needed.
  371. KeepHijackedConns bool
  372. // CloseOnShutdown when true adds a `Connection: close` header when the server is shutting down.
  373. CloseOnShutdown bool
  374. // StreamRequestBody enables request body streaming,
  375. // and calls the handler sooner when given body is
  376. // larger than the current limit.
  377. StreamRequestBody bool
  378. }
  379. // TimeoutHandler creates RequestHandler, which returns StatusRequestTimeout
  380. // error with the given msg to the client if h didn't return during
  381. // the given duration.
  382. //
  383. // The returned handler may return StatusTooManyRequests error with the given
  384. // msg to the client if there are more than Server.Concurrency concurrent
  385. // handlers h are running at the moment.
  386. func TimeoutHandler(h RequestHandler, timeout time.Duration, msg string) RequestHandler {
  387. return TimeoutWithCodeHandler(h, timeout, msg, StatusRequestTimeout)
  388. }
  389. // TimeoutWithCodeHandler creates RequestHandler, which returns an error with
  390. // the given msg and status code to the client if h didn't return during
  391. // the given duration.
  392. //
  393. // The returned handler may return StatusTooManyRequests error with the given
  394. // msg to the client if there are more than Server.Concurrency concurrent
  395. // handlers h are running at the moment.
  396. func TimeoutWithCodeHandler(h RequestHandler, timeout time.Duration, msg string, statusCode int) RequestHandler {
  397. if timeout <= 0 {
  398. return h
  399. }
  400. return func(ctx *RequestCtx) {
  401. concurrencyCh := ctx.s.concurrencyCh
  402. select {
  403. case concurrencyCh <- struct{}{}:
  404. default:
  405. ctx.Error(msg, StatusTooManyRequests)
  406. return
  407. }
  408. ch := ctx.timeoutCh
  409. if ch == nil {
  410. ch = make(chan struct{}, 1)
  411. ctx.timeoutCh = ch
  412. }
  413. go func() {
  414. h(ctx)
  415. ch <- struct{}{}
  416. <-concurrencyCh
  417. }()
  418. ctx.timeoutTimer = initTimer(ctx.timeoutTimer, timeout)
  419. select {
  420. case <-ch:
  421. case <-ctx.timeoutTimer.C:
  422. ctx.TimeoutErrorWithCode(msg, statusCode)
  423. }
  424. stopTimer(ctx.timeoutTimer)
  425. }
  426. }
  427. // RequestConfig configure the per request deadline and body limits.
  428. type RequestConfig struct {
  429. // ReadTimeout is the maximum duration for reading the entire
  430. // request body.
  431. // A zero value means that default values will be honored.
  432. ReadTimeout time.Duration
  433. // WriteTimeout is the maximum duration before timing out
  434. // writes of the response.
  435. // A zero value means that default values will be honored.
  436. WriteTimeout time.Duration
  437. // Maximum request body size.
  438. // A zero value means that default values will be honored.
  439. MaxRequestBodySize int
  440. }
  441. // CompressHandler returns RequestHandler that transparently compresses
  442. // response body generated by h if the request contains 'gzip' or 'deflate'
  443. // 'Accept-Encoding' header.
  444. func CompressHandler(h RequestHandler) RequestHandler {
  445. return CompressHandlerLevel(h, CompressDefaultCompression)
  446. }
  447. // CompressHandlerLevel returns RequestHandler that transparently compresses
  448. // response body generated by h if the request contains a 'gzip' or 'deflate'
  449. // 'Accept-Encoding' header.
  450. //
  451. // Level is the desired compression level:
  452. //
  453. // - CompressNoCompression
  454. // - CompressBestSpeed
  455. // - CompressBestCompression
  456. // - CompressDefaultCompression
  457. // - CompressHuffmanOnly
  458. func CompressHandlerLevel(h RequestHandler, level int) RequestHandler {
  459. return func(ctx *RequestCtx) {
  460. h(ctx)
  461. switch {
  462. case ctx.Request.Header.HasAcceptEncodingBytes(strGzip):
  463. ctx.Response.gzipBody(level)
  464. case ctx.Request.Header.HasAcceptEncodingBytes(strDeflate):
  465. ctx.Response.deflateBody(level)
  466. case ctx.Request.Header.HasAcceptEncodingBytes(strZstd):
  467. ctx.Response.zstdBody(level)
  468. }
  469. }
  470. }
  471. // CompressHandlerBrotliLevel returns RequestHandler that transparently compresses
  472. // response body generated by h if the request contains a 'br', 'gzip' or 'deflate'
  473. // 'Accept-Encoding' header.
  474. //
  475. // brotliLevel is the desired compression level for brotli.
  476. //
  477. // - CompressBrotliNoCompression
  478. // - CompressBrotliBestSpeed
  479. // - CompressBrotliBestCompression
  480. // - CompressBrotliDefaultCompression
  481. //
  482. // otherLevel is the desired compression level for gzip and deflate.
  483. //
  484. // - CompressNoCompression
  485. // - CompressBestSpeed
  486. // - CompressBestCompression
  487. // - CompressDefaultCompression
  488. // - CompressHuffmanOnly
  489. func CompressHandlerBrotliLevel(h RequestHandler, brotliLevel, otherLevel int) RequestHandler {
  490. return func(ctx *RequestCtx) {
  491. h(ctx)
  492. switch {
  493. case ctx.Request.Header.HasAcceptEncodingBytes(strBr):
  494. ctx.Response.brotliBody(brotliLevel)
  495. case ctx.Request.Header.HasAcceptEncodingBytes(strGzip):
  496. ctx.Response.gzipBody(otherLevel)
  497. case ctx.Request.Header.HasAcceptEncodingBytes(strDeflate):
  498. ctx.Response.deflateBody(otherLevel)
  499. case ctx.Request.Header.HasAcceptEncodingBytes(strZstd):
  500. ctx.Response.zstdBody(otherLevel)
  501. }
  502. }
  503. }
  504. // RequestCtx contains incoming request and manages outgoing response.
  505. //
  506. // It is forbidden copying RequestCtx instances.
  507. //
  508. // RequestHandler should avoid holding references to incoming RequestCtx and/or
  509. // its members after the return.
  510. // If holding RequestCtx references after the return is unavoidable
  511. // (for instance, ctx is passed to a separate goroutine and ctx lifetime cannot
  512. // be controlled), then the RequestHandler MUST call ctx.TimeoutError()
  513. // before return.
  514. //
  515. // It is unsafe modifying/reading RequestCtx instance from concurrently
  516. // running goroutines. The only exception is TimeoutError*, which may be called
  517. // while other goroutines accessing RequestCtx.
  518. type RequestCtx struct {
  519. noCopy noCopy
  520. // Outgoing response.
  521. //
  522. // Copying Response by value is forbidden. Use pointer to Response instead.
  523. Response Response
  524. connTime time.Time
  525. time time.Time
  526. logger ctxLogger
  527. remoteAddr net.Addr
  528. c net.Conn
  529. s *Server
  530. timeoutResponse *Response
  531. timeoutCh chan struct{}
  532. timeoutTimer *time.Timer
  533. hijackHandler HijackHandler
  534. formValueFunc FormValueFunc
  535. fbr firstByteReader
  536. userValues userData
  537. // Incoming request.
  538. //
  539. // Copying Request by value is forbidden. Use pointer to Request instead.
  540. Request Request
  541. connID uint64
  542. connRequestNum uint64
  543. hijackNoResponse bool
  544. }
  545. // HijackHandler must process the hijacked connection c.
  546. //
  547. // If KeepHijackedConns is disabled, which is by default,
  548. // the connection c is automatically closed after returning from HijackHandler.
  549. //
  550. // The connection c must not be used after returning from the handler, if KeepHijackedConns is disabled.
  551. //
  552. // When KeepHijackedConns enabled, fasthttp will not Close() the connection,
  553. // you must do it when you need it. You must not use c in any way after calling Close().
  554. type HijackHandler func(c net.Conn)
  555. // Hijack registers the given handler for connection hijacking.
  556. //
  557. // The handler is called after returning from RequestHandler
  558. // and sending http response. The current connection is passed
  559. // to the handler. The connection is automatically closed after
  560. // returning from the handler.
  561. //
  562. // The server skips calling the handler in the following cases:
  563. //
  564. // - 'Connection: close' header exists in either request or response.
  565. // - Unexpected error during response writing to the connection.
  566. //
  567. // The server stops processing requests from hijacked connections.
  568. //
  569. // Server limits such as Concurrency, ReadTimeout, WriteTimeout, etc.
  570. // aren't applied to hijacked connections.
  571. //
  572. // The handler must not retain references to ctx members.
  573. //
  574. // Arbitrary 'Connection: Upgrade' protocols may be implemented
  575. // with HijackHandler. For instance,
  576. //
  577. // - WebSocket ( https://en.wikipedia.org/wiki/WebSocket )
  578. // - HTTP/2.0 ( https://en.wikipedia.org/wiki/HTTP/2 )
  579. func (ctx *RequestCtx) Hijack(handler HijackHandler) {
  580. ctx.hijackHandler = handler
  581. }
  582. // HijackSetNoResponse changes the behavior of hijacking a request.
  583. // If HijackSetNoResponse is called with false fasthttp will send a response
  584. // to the client before calling the HijackHandler (default). If HijackSetNoResponse
  585. // is called with true no response is send back before calling the
  586. // HijackHandler supplied in the Hijack function.
  587. func (ctx *RequestCtx) HijackSetNoResponse(noResponse bool) {
  588. ctx.hijackNoResponse = noResponse
  589. }
  590. // Hijacked returns true after Hijack is called.
  591. func (ctx *RequestCtx) Hijacked() bool {
  592. return ctx.hijackHandler != nil
  593. }
  594. // SetUserValue stores the given value (arbitrary object)
  595. // under the given key in ctx.
  596. //
  597. // The value stored in ctx may be obtained by UserValue*.
  598. //
  599. // This functionality may be useful for passing arbitrary values between
  600. // functions involved in request processing.
  601. //
  602. // All the values are removed from ctx after returning from the top
  603. // RequestHandler. Additionally, Close method is called on each value
  604. // implementing io.Closer before removing the value from ctx.
  605. func (ctx *RequestCtx) SetUserValue(key, value any) {
  606. ctx.userValues.Set(key, value)
  607. }
  608. // SetUserValueBytes stores the given value (arbitrary object)
  609. // under the given key in ctx.
  610. //
  611. // The value stored in ctx may be obtained by UserValue*.
  612. //
  613. // This functionality may be useful for passing arbitrary values between
  614. // functions involved in request processing.
  615. //
  616. // All the values stored in ctx are deleted after returning from RequestHandler.
  617. func (ctx *RequestCtx) SetUserValueBytes(key []byte, value any) {
  618. ctx.userValues.SetBytes(key, value)
  619. }
  620. // UserValue returns the value stored via SetUserValue* under the given key.
  621. func (ctx *RequestCtx) UserValue(key any) any {
  622. return ctx.userValues.Get(key)
  623. }
  624. // UserValueBytes returns the value stored via SetUserValue*
  625. // under the given key.
  626. func (ctx *RequestCtx) UserValueBytes(key []byte) any {
  627. return ctx.userValues.GetBytes(key)
  628. }
  629. // VisitUserValues calls visitor for each existing userValue with a key that is a string or []byte.
  630. //
  631. // visitor must not retain references to key and value after returning.
  632. // Make key and/or value copies if you need storing them after returning.
  633. func (ctx *RequestCtx) VisitUserValues(visitor func([]byte, any)) {
  634. for i, n := 0, len(ctx.userValues); i < n; i++ {
  635. kv := &ctx.userValues[i]
  636. if _, ok := kv.key.(string); ok {
  637. visitor(s2b(kv.key.(string)), kv.value)
  638. }
  639. }
  640. }
  641. // VisitUserValuesAll calls visitor for each existing userValue.
  642. //
  643. // visitor must not retain references to key and value after returning.
  644. // Make key and/or value copies if you need storing them after returning.
  645. func (ctx *RequestCtx) VisitUserValuesAll(visitor func(any, any)) {
  646. for i, n := 0, len(ctx.userValues); i < n; i++ {
  647. kv := &ctx.userValues[i]
  648. visitor(kv.key, kv.value)
  649. }
  650. }
  651. // ResetUserValues allows to reset user values from Request Context.
  652. func (ctx *RequestCtx) ResetUserValues() {
  653. ctx.userValues.Reset()
  654. }
  655. // RemoveUserValue removes the given key and the value under it in ctx.
  656. func (ctx *RequestCtx) RemoveUserValue(key any) {
  657. ctx.userValues.Remove(key)
  658. }
  659. // RemoveUserValueBytes removes the given key and the value under it in ctx.
  660. func (ctx *RequestCtx) RemoveUserValueBytes(key []byte) {
  661. ctx.userValues.RemoveBytes(key)
  662. }
  663. type connTLSer interface {
  664. Handshake() error
  665. ConnectionState() tls.ConnectionState
  666. }
  667. // IsTLS returns true if the underlying connection is tls.Conn.
  668. //
  669. // tls.Conn is an encrypted connection (aka SSL, HTTPS).
  670. func (ctx *RequestCtx) IsTLS() bool {
  671. // cast to (connTLSer) instead of (*tls.Conn), since it catches
  672. // cases with overridden tls.Conn such as:
  673. //
  674. // type customConn struct {
  675. // *tls.Conn
  676. //
  677. // // other custom fields here
  678. // }
  679. // perIPConn wraps the net.Conn in the Conn field
  680. if pic, ok := ctx.c.(*perIPConn); ok {
  681. _, ok := pic.Conn.(connTLSer)
  682. return ok
  683. }
  684. _, ok := ctx.c.(connTLSer)
  685. return ok
  686. }
  687. // TLSConnectionState returns TLS connection state.
  688. //
  689. // The function returns nil if the underlying connection isn't tls.Conn.
  690. //
  691. // The returned state may be used for verifying TLS version, client certificates,
  692. // etc.
  693. func (ctx *RequestCtx) TLSConnectionState() *tls.ConnectionState {
  694. tlsConn, ok := ctx.c.(connTLSer)
  695. if !ok {
  696. return nil
  697. }
  698. state := tlsConn.ConnectionState()
  699. return &state
  700. }
  701. // Conn returns a reference to the underlying net.Conn.
  702. //
  703. // WARNING: Only use this method if you know what you are doing!
  704. //
  705. // Reading from or writing to the returned connection will end badly!
  706. func (ctx *RequestCtx) Conn() net.Conn {
  707. return ctx.c
  708. }
  709. func (ctx *RequestCtx) reset() {
  710. ctx.userValues.Reset()
  711. ctx.Request.Reset()
  712. ctx.Response.Reset()
  713. ctx.fbr.reset()
  714. ctx.connID = 0
  715. ctx.connRequestNum = 0
  716. ctx.connTime = zeroTime
  717. ctx.remoteAddr = nil
  718. ctx.time = zeroTime
  719. ctx.c = nil
  720. // Don't reset ctx.s!
  721. // We have a pool per server so the next time this ctx is used it
  722. // will be assigned the same value again.
  723. // ctx might still be in use for context.Done() and context.Err()
  724. // which are safe to use as they only use ctx.s and no other value.
  725. if ctx.timeoutResponse != nil {
  726. ctx.timeoutResponse.Reset()
  727. }
  728. if ctx.timeoutTimer != nil {
  729. stopTimer(ctx.timeoutTimer)
  730. }
  731. ctx.hijackHandler = nil
  732. ctx.hijackNoResponse = false
  733. }
  734. type firstByteReader struct {
  735. c net.Conn
  736. ch byte
  737. byteRead bool
  738. }
  739. func (r *firstByteReader) reset() {
  740. r.c = nil
  741. r.ch = 0
  742. r.byteRead = false
  743. }
  744. func (r *firstByteReader) Read(b []byte) (int, error) {
  745. if len(b) == 0 {
  746. return 0, nil
  747. }
  748. nn := 0
  749. if !r.byteRead {
  750. b[0] = r.ch
  751. b = b[1:]
  752. r.byteRead = true
  753. nn = 1
  754. }
  755. n, err := r.c.Read(b)
  756. return n + nn, err
  757. }
  758. // Logger is used for logging formatted messages.
  759. type Logger interface {
  760. // Printf must have the same semantics as log.Printf.
  761. Printf(format string, args ...any)
  762. }
  763. var ctxLoggerLock sync.Mutex
  764. type ctxLogger struct {
  765. ctx *RequestCtx
  766. logger Logger
  767. }
  768. func (cl *ctxLogger) Printf(format string, args ...any) {
  769. msg := fmt.Sprintf(format, args...)
  770. ctxLoggerLock.Lock()
  771. cl.logger.Printf("%.3f %s - %s", time.Since(cl.ctx.ConnTime()).Seconds(), cl.ctx.String(), msg)
  772. ctxLoggerLock.Unlock()
  773. }
  774. var zeroTCPAddr = &net.TCPAddr{
  775. IP: net.IPv4zero,
  776. }
  777. // String returns unique string representation of the ctx.
  778. //
  779. // The returned value may be useful for logging.
  780. func (ctx *RequestCtx) String() string {
  781. return fmt.Sprintf("#%016X - %s<->%s - %s %s", ctx.ID(), ctx.LocalAddr(), ctx.RemoteAddr(),
  782. ctx.Request.Header.Method(), ctx.URI().FullURI())
  783. }
  784. // ID returns unique ID of the request.
  785. func (ctx *RequestCtx) ID() uint64 {
  786. return (ctx.connID << 32) | ctx.connRequestNum
  787. }
  788. // ConnID returns unique connection ID.
  789. //
  790. // This ID may be used to match distinct requests to the same incoming
  791. // connection.
  792. func (ctx *RequestCtx) ConnID() uint64 {
  793. return ctx.connID
  794. }
  795. // Time returns RequestHandler call time.
  796. func (ctx *RequestCtx) Time() time.Time {
  797. return ctx.time
  798. }
  799. // ConnTime returns the time the server started serving the connection
  800. // the current request came from.
  801. func (ctx *RequestCtx) ConnTime() time.Time {
  802. return ctx.connTime
  803. }
  804. // ConnRequestNum returns request sequence number
  805. // for the current connection.
  806. //
  807. // Sequence starts with 1.
  808. func (ctx *RequestCtx) ConnRequestNum() uint64 {
  809. return ctx.connRequestNum
  810. }
  811. // SetConnectionClose sets 'Connection: close' response header and closes
  812. // connection after the RequestHandler returns.
  813. func (ctx *RequestCtx) SetConnectionClose() {
  814. ctx.Response.SetConnectionClose()
  815. }
  816. // SetStatusCode sets response status code.
  817. func (ctx *RequestCtx) SetStatusCode(statusCode int) {
  818. ctx.Response.SetStatusCode(statusCode)
  819. }
  820. // SetContentType sets response Content-Type.
  821. func (ctx *RequestCtx) SetContentType(contentType string) {
  822. ctx.Response.Header.SetContentType(contentType)
  823. }
  824. // SetContentTypeBytes sets response Content-Type.
  825. //
  826. // It is safe modifying contentType buffer after function return.
  827. func (ctx *RequestCtx) SetContentTypeBytes(contentType []byte) {
  828. ctx.Response.Header.SetContentTypeBytes(contentType)
  829. }
  830. // RequestURI returns RequestURI.
  831. //
  832. // The returned bytes are valid until your request handler returns.
  833. func (ctx *RequestCtx) RequestURI() []byte {
  834. return ctx.Request.Header.RequestURI()
  835. }
  836. // URI returns requested uri.
  837. //
  838. // This uri is valid until your request handler returns.
  839. func (ctx *RequestCtx) URI() *URI {
  840. return ctx.Request.URI()
  841. }
  842. // Referer returns request referer.
  843. //
  844. // The returned bytes are valid until your request handler returns.
  845. func (ctx *RequestCtx) Referer() []byte {
  846. return ctx.Request.Header.Referer()
  847. }
  848. // UserAgent returns User-Agent header value from the request.
  849. //
  850. // The returned bytes are valid until your request handler returns.
  851. func (ctx *RequestCtx) UserAgent() []byte {
  852. return ctx.Request.Header.UserAgent()
  853. }
  854. // Path returns requested path.
  855. //
  856. // The returned bytes are valid until your request handler returns.
  857. func (ctx *RequestCtx) Path() []byte {
  858. return ctx.URI().Path()
  859. }
  860. // Host returns requested host.
  861. //
  862. // The returned bytes are valid until your request handler returns.
  863. func (ctx *RequestCtx) Host() []byte {
  864. return ctx.URI().Host()
  865. }
  866. // QueryArgs returns query arguments from RequestURI.
  867. //
  868. // It doesn't return POST'ed arguments - use PostArgs() for this.
  869. //
  870. // See also PostArgs, FormValue and FormFile.
  871. //
  872. // These args are valid until your request handler returns.
  873. func (ctx *RequestCtx) QueryArgs() *Args {
  874. return ctx.URI().QueryArgs()
  875. }
  876. // PostArgs returns POST arguments.
  877. //
  878. // It doesn't return query arguments from RequestURI - use QueryArgs for this.
  879. //
  880. // See also QueryArgs, FormValue and FormFile.
  881. //
  882. // These args are valid until your request handler returns.
  883. func (ctx *RequestCtx) PostArgs() *Args {
  884. return ctx.Request.PostArgs()
  885. }
  886. // MultipartForm returns request's multipart form.
  887. //
  888. // Returns ErrNoMultipartForm if request's content-type
  889. // isn't 'multipart/form-data'.
  890. //
  891. // All uploaded temporary files are automatically deleted after
  892. // returning from RequestHandler. Either move or copy uploaded files
  893. // into new place if you want retaining them.
  894. //
  895. // Use SaveMultipartFile function for permanently saving uploaded file.
  896. //
  897. // The returned form is valid until your request handler returns.
  898. //
  899. // See also FormFile and FormValue.
  900. func (ctx *RequestCtx) MultipartForm() (*multipart.Form, error) {
  901. return ctx.Request.MultipartForm()
  902. }
  903. // FormFile returns uploaded file associated with the given multipart form key.
  904. //
  905. // The file is automatically deleted after returning from RequestHandler,
  906. // so either move or copy uploaded file into new place if you want retaining it.
  907. //
  908. // Use SaveMultipartFile function for permanently saving uploaded file.
  909. //
  910. // The returned file header is valid until your request handler returns.
  911. func (ctx *RequestCtx) FormFile(key string) (*multipart.FileHeader, error) {
  912. mf, err := ctx.MultipartForm()
  913. if err != nil {
  914. return nil, err
  915. }
  916. if mf.File == nil {
  917. return nil, err
  918. }
  919. fhh := mf.File[key]
  920. if fhh == nil {
  921. return nil, ErrMissingFile
  922. }
  923. return fhh[0], nil
  924. }
  925. // ErrMissingFile may be returned from FormFile when the is no uploaded file
  926. // associated with the given multipart form key.
  927. var ErrMissingFile = errors.New("there is no uploaded file associated with the given key")
  928. // SaveMultipartFile saves multipart file fh under the given filename path.
  929. func SaveMultipartFile(fh *multipart.FileHeader, path string) (err error) {
  930. var (
  931. f multipart.File
  932. ff *os.File
  933. )
  934. f, err = fh.Open()
  935. if err != nil {
  936. return
  937. }
  938. var ok bool
  939. if ff, ok = f.(*os.File); ok {
  940. // Windows can't rename files that are opened.
  941. if err = f.Close(); err != nil {
  942. return
  943. }
  944. // If renaming fails we try the normal copying method.
  945. // Renaming could fail if the files are on different devices.
  946. if os.Rename(ff.Name(), path) == nil {
  947. return nil
  948. }
  949. // Reopen f for the code below.
  950. if f, err = fh.Open(); err != nil {
  951. return
  952. }
  953. }
  954. defer func() {
  955. e := f.Close()
  956. if err == nil {
  957. err = e
  958. }
  959. }()
  960. if ff, err = os.Create(path); err != nil {
  961. return
  962. }
  963. defer func() {
  964. e := ff.Close()
  965. if err == nil {
  966. err = e
  967. }
  968. }()
  969. _, err = copyZeroAlloc(ff, f)
  970. return
  971. }
  972. // FormValue returns form value associated with the given key.
  973. //
  974. // The value is searched in the following places:
  975. //
  976. // - Query string.
  977. // - POST or PUT body.
  978. //
  979. // There are more fine-grained methods for obtaining form values:
  980. //
  981. // - QueryArgs for obtaining values from query string.
  982. // - PostArgs for obtaining values from POST or PUT body.
  983. // - MultipartForm for obtaining values from multipart form.
  984. // - FormFile for obtaining uploaded files.
  985. //
  986. // The returned value is valid until your request handler returns.
  987. func (ctx *RequestCtx) FormValue(key string) []byte {
  988. if ctx.formValueFunc != nil {
  989. return ctx.formValueFunc(ctx, key)
  990. }
  991. return defaultFormValue(ctx, key)
  992. }
  993. type FormValueFunc func(*RequestCtx, string) []byte
  994. var (
  995. defaultFormValue = func(ctx *RequestCtx, key string) []byte {
  996. v := ctx.QueryArgs().Peek(key)
  997. if len(v) > 0 {
  998. return v
  999. }
  1000. v = ctx.PostArgs().Peek(key)
  1001. if len(v) > 0 {
  1002. return v
  1003. }
  1004. mf, err := ctx.MultipartForm()
  1005. if err == nil && mf.Value != nil {
  1006. vv := mf.Value[key]
  1007. if len(vv) > 0 {
  1008. return []byte(vv[0])
  1009. }
  1010. }
  1011. return nil
  1012. }
  1013. // NetHttpFormValueFunc gives consistent behavior with net/http.
  1014. // POST and PUT body parameters take precedence over URL query string values.
  1015. //
  1016. //nolint:stylecheck // backwards compatibility
  1017. NetHttpFormValueFunc = func(ctx *RequestCtx, key string) []byte {
  1018. v := ctx.PostArgs().Peek(key)
  1019. if len(v) > 0 {
  1020. return v
  1021. }
  1022. mf, err := ctx.MultipartForm()
  1023. if err == nil && mf.Value != nil {
  1024. vv := mf.Value[key]
  1025. if len(vv) > 0 {
  1026. return []byte(vv[0])
  1027. }
  1028. }
  1029. v = ctx.QueryArgs().Peek(key)
  1030. if len(v) > 0 {
  1031. return v
  1032. }
  1033. return nil
  1034. }
  1035. )
  1036. // IsGet returns true if request method is GET.
  1037. func (ctx *RequestCtx) IsGet() bool {
  1038. return ctx.Request.Header.IsGet()
  1039. }
  1040. // IsPost returns true if request method is POST.
  1041. func (ctx *RequestCtx) IsPost() bool {
  1042. return ctx.Request.Header.IsPost()
  1043. }
  1044. // IsPut returns true if request method is PUT.
  1045. func (ctx *RequestCtx) IsPut() bool {
  1046. return ctx.Request.Header.IsPut()
  1047. }
  1048. // IsDelete returns true if request method is DELETE.
  1049. func (ctx *RequestCtx) IsDelete() bool {
  1050. return ctx.Request.Header.IsDelete()
  1051. }
  1052. // IsConnect returns true if request method is CONNECT.
  1053. func (ctx *RequestCtx) IsConnect() bool {
  1054. return ctx.Request.Header.IsConnect()
  1055. }
  1056. // IsOptions returns true if request method is OPTIONS.
  1057. func (ctx *RequestCtx) IsOptions() bool {
  1058. return ctx.Request.Header.IsOptions()
  1059. }
  1060. // IsTrace returns true if request method is TRACE.
  1061. func (ctx *RequestCtx) IsTrace() bool {
  1062. return ctx.Request.Header.IsTrace()
  1063. }
  1064. // IsPatch returns true if request method is PATCH.
  1065. func (ctx *RequestCtx) IsPatch() bool {
  1066. return ctx.Request.Header.IsPatch()
  1067. }
  1068. // Method return request method.
  1069. //
  1070. // Returned value is valid until your request handler returns.
  1071. func (ctx *RequestCtx) Method() []byte {
  1072. return ctx.Request.Header.Method()
  1073. }
  1074. // IsHead returns true if request method is HEAD.
  1075. func (ctx *RequestCtx) IsHead() bool {
  1076. return ctx.Request.Header.IsHead()
  1077. }
  1078. // RemoteAddr returns client address for the given request.
  1079. //
  1080. // Always returns non-nil result.
  1081. func (ctx *RequestCtx) RemoteAddr() net.Addr {
  1082. if ctx.remoteAddr != nil {
  1083. return ctx.remoteAddr
  1084. }
  1085. if ctx.c == nil {
  1086. return zeroTCPAddr
  1087. }
  1088. addr := ctx.c.RemoteAddr()
  1089. if addr == nil {
  1090. return zeroTCPAddr
  1091. }
  1092. return addr
  1093. }
  1094. // SetRemoteAddr sets remote address to the given value.
  1095. //
  1096. // Set nil value to restore default behaviour for using
  1097. // connection remote address.
  1098. func (ctx *RequestCtx) SetRemoteAddr(remoteAddr net.Addr) {
  1099. ctx.remoteAddr = remoteAddr
  1100. }
  1101. // LocalAddr returns server address for the given request.
  1102. //
  1103. // Always returns non-nil result.
  1104. func (ctx *RequestCtx) LocalAddr() net.Addr {
  1105. if ctx.c == nil {
  1106. return zeroTCPAddr
  1107. }
  1108. addr := ctx.c.LocalAddr()
  1109. if addr == nil {
  1110. return zeroTCPAddr
  1111. }
  1112. return addr
  1113. }
  1114. // RemoteIP returns the client ip the request came from.
  1115. //
  1116. // Always returns non-nil result.
  1117. func (ctx *RequestCtx) RemoteIP() net.IP {
  1118. return addrToIP(ctx.RemoteAddr())
  1119. }
  1120. // LocalIP returns the server ip the request came to.
  1121. //
  1122. // Always returns non-nil result.
  1123. func (ctx *RequestCtx) LocalIP() net.IP {
  1124. return addrToIP(ctx.LocalAddr())
  1125. }
  1126. func addrToIP(addr net.Addr) net.IP {
  1127. x, ok := addr.(*net.TCPAddr)
  1128. if !ok {
  1129. return net.IPv4zero
  1130. }
  1131. return x.IP
  1132. }
  1133. // Error sets response status code to the given value and sets response body
  1134. // to the given message.
  1135. //
  1136. // Warning: this will reset the response headers and body already set!
  1137. func (ctx *RequestCtx) Error(msg string, statusCode int) {
  1138. ctx.Response.Reset()
  1139. ctx.SetStatusCode(statusCode)
  1140. ctx.SetContentTypeBytes(defaultContentType)
  1141. ctx.SetBodyString(msg)
  1142. }
  1143. // Success sets response Content-Type and body to the given values.
  1144. func (ctx *RequestCtx) Success(contentType string, body []byte) {
  1145. ctx.SetContentType(contentType)
  1146. ctx.SetBody(body)
  1147. }
  1148. // SuccessString sets response Content-Type and body to the given values.
  1149. func (ctx *RequestCtx) SuccessString(contentType, body string) {
  1150. ctx.SetContentType(contentType)
  1151. ctx.SetBodyString(body)
  1152. }
  1153. // Redirect sets 'Location: uri' response header and sets the given statusCode.
  1154. //
  1155. // statusCode must have one of the following values:
  1156. //
  1157. // - StatusMovedPermanently (301)
  1158. // - StatusFound (302)
  1159. // - StatusSeeOther (303)
  1160. // - StatusTemporaryRedirect (307)
  1161. // - StatusPermanentRedirect (308)
  1162. //
  1163. // All other statusCode values are replaced by StatusFound (302).
  1164. //
  1165. // The redirect uri may be either absolute or relative to the current
  1166. // request uri. Fasthttp will always send an absolute uri back to the client.
  1167. // To send a relative uri you can use the following code:
  1168. //
  1169. // strLocation = []byte("Location") // Put this with your top level var () declarations.
  1170. // ctx.Response.Header.SetCanonical(strLocation, "/relative?uri")
  1171. // ctx.Response.SetStatusCode(fasthttp.StatusMovedPermanently)
  1172. func (ctx *RequestCtx) Redirect(uri string, statusCode int) {
  1173. u := AcquireURI()
  1174. ctx.URI().CopyTo(u)
  1175. u.Update(uri)
  1176. ctx.redirect(u.FullURI(), statusCode)
  1177. ReleaseURI(u)
  1178. }
  1179. // RedirectBytes sets 'Location: uri' response header and sets
  1180. // the given statusCode.
  1181. //
  1182. // statusCode must have one of the following values:
  1183. //
  1184. // - StatusMovedPermanently (301)
  1185. // - StatusFound (302)
  1186. // - StatusSeeOther (303)
  1187. // - StatusTemporaryRedirect (307)
  1188. // - StatusPermanentRedirect (308)
  1189. //
  1190. // All other statusCode values are replaced by StatusFound (302).
  1191. //
  1192. // The redirect uri may be either absolute or relative to the current
  1193. // request uri. Fasthttp will always send an absolute uri back to the client.
  1194. // To send a relative uri you can use the following code:
  1195. //
  1196. // strLocation = []byte("Location") // Put this with your top level var () declarations.
  1197. // ctx.Response.Header.SetCanonical(strLocation, "/relative?uri")
  1198. // ctx.Response.SetStatusCode(fasthttp.StatusMovedPermanently)
  1199. func (ctx *RequestCtx) RedirectBytes(uri []byte, statusCode int) {
  1200. s := b2s(uri)
  1201. ctx.Redirect(s, statusCode)
  1202. }
  1203. func (ctx *RequestCtx) redirect(uri []byte, statusCode int) {
  1204. ctx.Response.Header.setNonSpecial(strLocation, uri)
  1205. statusCode = getRedirectStatusCode(statusCode)
  1206. ctx.Response.SetStatusCode(statusCode)
  1207. }
  1208. func getRedirectStatusCode(statusCode int) int {
  1209. if statusCode == StatusMovedPermanently || statusCode == StatusFound ||
  1210. statusCode == StatusSeeOther || statusCode == StatusTemporaryRedirect ||
  1211. statusCode == StatusPermanentRedirect {
  1212. return statusCode
  1213. }
  1214. return StatusFound
  1215. }
  1216. // SetBody sets response body to the given value.
  1217. //
  1218. // It is safe re-using body argument after the function returns.
  1219. func (ctx *RequestCtx) SetBody(body []byte) {
  1220. ctx.Response.SetBody(body)
  1221. }
  1222. // SetBodyString sets response body to the given value.
  1223. func (ctx *RequestCtx) SetBodyString(body string) {
  1224. ctx.Response.SetBodyString(body)
  1225. }
  1226. // ResetBody resets response body contents.
  1227. func (ctx *RequestCtx) ResetBody() {
  1228. ctx.Response.ResetBody()
  1229. }
  1230. // SendFile sends local file contents from the given path as response body.
  1231. //
  1232. // This is a shortcut to ServeFile(ctx, path).
  1233. //
  1234. // SendFile logs all the errors via ctx.Logger.
  1235. //
  1236. // See also ServeFile, FSHandler and FS.
  1237. //
  1238. // WARNING: do not pass any user supplied paths to this function!
  1239. // WARNING: if path is based on user input users will be able to request
  1240. // any file on your filesystem! Use fasthttp.FS with a sane Root instead.
  1241. func (ctx *RequestCtx) SendFile(path string) {
  1242. ServeFile(ctx, path)
  1243. }
  1244. // SendFileBytes sends local file contents from the given path as response body.
  1245. //
  1246. // This is a shortcut to ServeFileBytes(ctx, path).
  1247. //
  1248. // SendFileBytes logs all the errors via ctx.Logger.
  1249. //
  1250. // See also ServeFileBytes, FSHandler and FS.
  1251. //
  1252. // WARNING: do not pass any user supplied paths to this function!
  1253. // WARNING: if path is based on user input users will be able to request
  1254. // any file on your filesystem! Use fasthttp.FS with a sane Root instead.
  1255. func (ctx *RequestCtx) SendFileBytes(path []byte) {
  1256. ServeFileBytes(ctx, path)
  1257. }
  1258. // IfModifiedSince returns true if lastModified exceeds 'If-Modified-Since'
  1259. // value from the request header.
  1260. //
  1261. // The function returns true also 'If-Modified-Since' request header is missing.
  1262. func (ctx *RequestCtx) IfModifiedSince(lastModified time.Time) bool {
  1263. ifModStr := ctx.Request.Header.peek(strIfModifiedSince)
  1264. if len(ifModStr) == 0 {
  1265. return true
  1266. }
  1267. ifMod, err := ParseHTTPDate(ifModStr)
  1268. if err != nil {
  1269. return true
  1270. }
  1271. lastModified = lastModified.Truncate(time.Second)
  1272. return ifMod.Before(lastModified)
  1273. }
  1274. // NotModified resets response and sets '304 Not Modified' response status code.
  1275. func (ctx *RequestCtx) NotModified() {
  1276. ctx.Response.Reset()
  1277. ctx.SetStatusCode(StatusNotModified)
  1278. }
  1279. // NotFound resets response and sets '404 Not Found' response status code.
  1280. func (ctx *RequestCtx) NotFound() {
  1281. ctx.Response.Reset()
  1282. ctx.SetStatusCode(StatusNotFound)
  1283. ctx.SetBodyString("404 Page not found")
  1284. }
  1285. // Write writes p into response body.
  1286. func (ctx *RequestCtx) Write(p []byte) (int, error) {
  1287. ctx.Response.AppendBody(p)
  1288. return len(p), nil
  1289. }
  1290. // WriteString appends s to response body.
  1291. func (ctx *RequestCtx) WriteString(s string) (int, error) {
  1292. ctx.Response.AppendBodyString(s)
  1293. return len(s), nil
  1294. }
  1295. // PostBody returns POST request body.
  1296. //
  1297. // The returned bytes are valid until your request handler returns.
  1298. func (ctx *RequestCtx) PostBody() []byte {
  1299. return ctx.Request.Body()
  1300. }
  1301. // SetBodyStream sets response body stream and, optionally body size.
  1302. //
  1303. // bodyStream.Close() is called after finishing reading all body data
  1304. // if it implements io.Closer.
  1305. //
  1306. // If bodySize is >= 0, then bodySize bytes must be provided by bodyStream
  1307. // before returning io.EOF.
  1308. //
  1309. // If bodySize < 0, then bodyStream is read until io.EOF.
  1310. //
  1311. // See also SetBodyStreamWriter.
  1312. func (ctx *RequestCtx) SetBodyStream(bodyStream io.Reader, bodySize int) {
  1313. ctx.Response.SetBodyStream(bodyStream, bodySize)
  1314. }
  1315. // SetBodyStreamWriter registers the given stream writer for populating
  1316. // response body.
  1317. //
  1318. // Access to RequestCtx and/or its members is forbidden from sw.
  1319. //
  1320. // This function may be used in the following cases:
  1321. //
  1322. // - if response body is too big (more than 10MB).
  1323. // - if response body is streamed from slow external sources.
  1324. // - if response body must be streamed to the client in chunks.
  1325. // (aka `http server push`).
  1326. func (ctx *RequestCtx) SetBodyStreamWriter(sw StreamWriter) {
  1327. ctx.Response.SetBodyStreamWriter(sw)
  1328. }
  1329. // IsBodyStream returns true if response body is set via SetBodyStream*.
  1330. func (ctx *RequestCtx) IsBodyStream() bool {
  1331. return ctx.Response.IsBodyStream()
  1332. }
  1333. // Logger returns logger, which may be used for logging arbitrary
  1334. // request-specific messages inside RequestHandler.
  1335. //
  1336. // Each message logged via returned logger contains request-specific information
  1337. // such as request id, request duration, local address, remote address,
  1338. // request method and request url.
  1339. //
  1340. // It is safe re-using returned logger for logging multiple messages
  1341. // for the current request.
  1342. //
  1343. // The returned logger is valid until your request handler returns.
  1344. func (ctx *RequestCtx) Logger() Logger {
  1345. if ctx.logger.ctx == nil {
  1346. ctx.logger.ctx = ctx
  1347. }
  1348. if ctx.logger.logger == nil {
  1349. ctx.logger.logger = ctx.s.logger()
  1350. }
  1351. return &ctx.logger
  1352. }
  1353. // TimeoutError sets response status code to StatusRequestTimeout and sets
  1354. // body to the given msg.
  1355. //
  1356. // All response modifications after TimeoutError call are ignored.
  1357. //
  1358. // TimeoutError MUST be called before returning from RequestHandler if there are
  1359. // references to ctx and/or its members in other goroutines remain.
  1360. //
  1361. // Usage of this function is discouraged. Prefer eliminating ctx references
  1362. // from pending goroutines instead of using this function.
  1363. func (ctx *RequestCtx) TimeoutError(msg string) {
  1364. ctx.TimeoutErrorWithCode(msg, StatusRequestTimeout)
  1365. }
  1366. // TimeoutErrorWithCode sets response body to msg and response status
  1367. // code to statusCode.
  1368. //
  1369. // All response modifications after TimeoutErrorWithCode call are ignored.
  1370. //
  1371. // TimeoutErrorWithCode MUST be called before returning from RequestHandler
  1372. // if there are references to ctx and/or its members in other goroutines remain.
  1373. //
  1374. // Usage of this function is discouraged. Prefer eliminating ctx references
  1375. // from pending goroutines instead of using this function.
  1376. func (ctx *RequestCtx) TimeoutErrorWithCode(msg string, statusCode int) {
  1377. var resp Response
  1378. resp.SetStatusCode(statusCode)
  1379. resp.SetBodyString(msg)
  1380. ctx.TimeoutErrorWithResponse(&resp)
  1381. }
  1382. // TimeoutErrorWithResponse marks the ctx as timed out and sends the given
  1383. // response to the client.
  1384. //
  1385. // All ctx modifications after TimeoutErrorWithResponse call are ignored.
  1386. //
  1387. // TimeoutErrorWithResponse MUST be called before returning from RequestHandler
  1388. // if there are references to ctx and/or its members in other goroutines remain.
  1389. //
  1390. // Usage of this function is discouraged. Prefer eliminating ctx references
  1391. // from pending goroutines instead of using this function.
  1392. func (ctx *RequestCtx) TimeoutErrorWithResponse(resp *Response) {
  1393. respCopy := &Response{}
  1394. resp.CopyTo(respCopy)
  1395. ctx.timeoutResponse = respCopy
  1396. }
  1397. // NextProto adds nph to be processed when key is negotiated when TLS
  1398. // connection is established.
  1399. //
  1400. // This function can only be called before the server is started.
  1401. func (s *Server) NextProto(key string, nph ServeHandler) {
  1402. if s.nextProtos == nil {
  1403. s.nextProtos = make(map[string]ServeHandler)
  1404. }
  1405. s.configTLS()
  1406. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, key)
  1407. s.nextProtos[key] = nph
  1408. }
  1409. func (s *Server) getNextProto(c net.Conn) (proto string, err error) {
  1410. if tlsConn, ok := c.(connTLSer); ok {
  1411. if s.ReadTimeout > 0 {
  1412. if err = c.SetReadDeadline(time.Now().Add(s.ReadTimeout)); err != nil {
  1413. return
  1414. }
  1415. }
  1416. if s.WriteTimeout > 0 {
  1417. if err = c.SetWriteDeadline(time.Now().Add(s.WriteTimeout)); err != nil {
  1418. return
  1419. }
  1420. }
  1421. err = tlsConn.Handshake()
  1422. if err == nil {
  1423. proto = tlsConn.ConnectionState().NegotiatedProtocol
  1424. }
  1425. }
  1426. return
  1427. }
  1428. // ListenAndServe serves HTTP requests from the given TCP4 addr.
  1429. //
  1430. // Pass custom listener to Serve if you need listening on non-TCP4 media
  1431. // such as IPv6.
  1432. //
  1433. // Accepted connections are configured to enable TCP keep-alives.
  1434. func (s *Server) ListenAndServe(addr string) error {
  1435. ln, err := net.Listen("tcp4", addr)
  1436. if err != nil {
  1437. return err
  1438. }
  1439. return s.Serve(ln)
  1440. }
  1441. // ListenAndServeUNIX serves HTTP requests from the given UNIX addr.
  1442. //
  1443. // The function deletes existing file at addr before starting serving.
  1444. //
  1445. // The server sets the given file mode for the UNIX addr.
  1446. func (s *Server) ListenAndServeUNIX(addr string, mode os.FileMode) error {
  1447. if err := os.Remove(addr); err != nil && !os.IsNotExist(err) {
  1448. return fmt.Errorf("unexpected error when trying to remove unix socket file %q: %w", addr, err)
  1449. }
  1450. ln, err := net.Listen("unix", addr)
  1451. if err != nil {
  1452. return err
  1453. }
  1454. if err = os.Chmod(addr, mode); err != nil {
  1455. return fmt.Errorf("cannot chmod %#o for %q: %w", mode, addr, err)
  1456. }
  1457. return s.Serve(ln)
  1458. }
  1459. // ListenAndServeTLS serves HTTPS requests from the given TCP4 addr.
  1460. //
  1461. // certFile and keyFile are paths to TLS certificate and key files.
  1462. //
  1463. // Pass custom listener to Serve if you need listening on non-TCP4 media
  1464. // such as IPv6.
  1465. //
  1466. // If the certFile or keyFile has not been provided to the server structure,
  1467. // the function will use the previously added TLS configuration.
  1468. //
  1469. // Accepted connections are configured to enable TCP keep-alives.
  1470. func (s *Server) ListenAndServeTLS(addr, certFile, keyFile string) error {
  1471. ln, err := net.Listen("tcp4", addr)
  1472. if err != nil {
  1473. return err
  1474. }
  1475. return s.ServeTLS(ln, certFile, keyFile)
  1476. }
  1477. // ListenAndServeTLSEmbed serves HTTPS requests from the given TCP4 addr.
  1478. //
  1479. // certData and keyData must contain valid TLS certificate and key data.
  1480. //
  1481. // Pass custom listener to Serve if you need listening on arbitrary media
  1482. // such as IPv6.
  1483. //
  1484. // If the certFile or keyFile has not been provided the server structure,
  1485. // the function will use previously added TLS configuration.
  1486. //
  1487. // Accepted connections are configured to enable TCP keep-alives.
  1488. func (s *Server) ListenAndServeTLSEmbed(addr string, certData, keyData []byte) error {
  1489. ln, err := net.Listen("tcp4", addr)
  1490. if err != nil {
  1491. return err
  1492. }
  1493. return s.ServeTLSEmbed(ln, certData, keyData)
  1494. }
  1495. // ServeTLS serves HTTPS requests from the given listener.
  1496. //
  1497. // certFile and keyFile are paths to TLS certificate and key files.
  1498. //
  1499. // If the certFile or keyFile has not been provided the server structure,
  1500. // the function will use previously added TLS configuration.
  1501. func (s *Server) ServeTLS(ln net.Listener, certFile, keyFile string) error {
  1502. s.mu.Lock()
  1503. s.configTLS()
  1504. configHasCert := len(s.TLSConfig.Certificates) > 0 || s.TLSConfig.GetCertificate != nil
  1505. if !configHasCert || certFile != "" || keyFile != "" {
  1506. if err := s.AppendCert(certFile, keyFile); err != nil {
  1507. s.mu.Unlock()
  1508. return err
  1509. }
  1510. }
  1511. // BuildNameToCertificate has been deprecated since 1.14.
  1512. // But since we also support older versions we'll keep this here.
  1513. s.TLSConfig.BuildNameToCertificate() //nolint:staticcheck
  1514. s.mu.Unlock()
  1515. return s.Serve(
  1516. tls.NewListener(ln, s.TLSConfig.Clone()),
  1517. )
  1518. }
  1519. // ServeTLSEmbed serves HTTPS requests from the given listener.
  1520. //
  1521. // certData and keyData must contain valid TLS certificate and key data.
  1522. //
  1523. // If the certFile or keyFile has not been provided the server structure,
  1524. // the function will use previously added TLS configuration.
  1525. func (s *Server) ServeTLSEmbed(ln net.Listener, certData, keyData []byte) error {
  1526. s.mu.Lock()
  1527. s.configTLS()
  1528. configHasCert := len(s.TLSConfig.Certificates) > 0 || s.TLSConfig.GetCertificate != nil
  1529. if !configHasCert || len(certData) != 0 || len(keyData) != 0 {
  1530. if err := s.AppendCertEmbed(certData, keyData); err != nil {
  1531. s.mu.Unlock()
  1532. return err
  1533. }
  1534. }
  1535. // BuildNameToCertificate has been deprecated since 1.14.
  1536. // But since we also support older versions we'll keep this here.
  1537. s.TLSConfig.BuildNameToCertificate() //nolint:staticcheck
  1538. s.mu.Unlock()
  1539. return s.Serve(
  1540. tls.NewListener(ln, s.TLSConfig.Clone()),
  1541. )
  1542. }
  1543. // AppendCert appends certificate and keyfile to TLS Configuration.
  1544. //
  1545. // This function allows programmer to handle multiple domains
  1546. // in one server structure. See examples/multidomain.
  1547. func (s *Server) AppendCert(certFile, keyFile string) error {
  1548. if certFile == "" && keyFile == "" {
  1549. return errNoCertOrKeyProvided
  1550. }
  1551. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  1552. if err != nil {
  1553. return fmt.Errorf("cannot load TLS key pair from certFile=%q and keyFile=%q: %w", certFile, keyFile, err)
  1554. }
  1555. s.configTLS()
  1556. s.TLSConfig.Certificates = append(s.TLSConfig.Certificates, cert)
  1557. return nil
  1558. }
  1559. // AppendCertEmbed does the same as AppendCert but using in-memory data.
  1560. func (s *Server) AppendCertEmbed(certData, keyData []byte) error {
  1561. if len(certData) == 0 && len(keyData) == 0 {
  1562. return errNoCertOrKeyProvided
  1563. }
  1564. cert, err := tls.X509KeyPair(certData, keyData)
  1565. if err != nil {
  1566. return fmt.Errorf("cannot load TLS key pair from the provided certData(%d) and keyData(%d): %w",
  1567. len(certData), len(keyData), err)
  1568. }
  1569. s.configTLS()
  1570. s.TLSConfig.Certificates = append(s.TLSConfig.Certificates, cert)
  1571. return nil
  1572. }
  1573. func (s *Server) configTLS() {
  1574. if s.TLSConfig == nil {
  1575. s.TLSConfig = &tls.Config{}
  1576. }
  1577. }
  1578. // DefaultConcurrency is the maximum number of concurrent connections
  1579. // the Server may serve by default (i.e. if Server.Concurrency isn't set).
  1580. const DefaultConcurrency = 256 * 1024
  1581. // Serve serves incoming connections from the given listener.
  1582. //
  1583. // Serve blocks until the given listener returns permanent error.
  1584. func (s *Server) Serve(ln net.Listener) error {
  1585. var lastOverflowErrorTime time.Time
  1586. var lastPerIPErrorTime time.Time
  1587. maxWorkersCount := s.getConcurrency()
  1588. s.mu.Lock()
  1589. s.ln = append(s.ln, ln)
  1590. if s.done == nil {
  1591. s.done = make(chan struct{})
  1592. }
  1593. if s.concurrencyCh == nil {
  1594. s.concurrencyCh = make(chan struct{}, maxWorkersCount)
  1595. }
  1596. s.mu.Unlock()
  1597. wp := &workerPool{
  1598. WorkerFunc: s.serveConn,
  1599. MaxWorkersCount: maxWorkersCount,
  1600. LogAllErrors: s.LogAllErrors,
  1601. MaxIdleWorkerDuration: s.MaxIdleWorkerDuration,
  1602. Logger: s.logger(),
  1603. connState: s.setState,
  1604. }
  1605. wp.Start()
  1606. // Count our waiting to accept a connection as an open connection.
  1607. // This way we can't get into any weird state where just after accepting
  1608. // a connection Shutdown is called which reads open as 0 because it isn't
  1609. // incremented yet.
  1610. atomic.AddInt32(&s.open, 1)
  1611. defer atomic.AddInt32(&s.open, -1)
  1612. for {
  1613. c, err := acceptConn(s, ln, &lastPerIPErrorTime)
  1614. if err != nil {
  1615. wp.Stop()
  1616. if err == io.EOF {
  1617. return nil
  1618. }
  1619. return err
  1620. }
  1621. s.setState(c, StateNew)
  1622. atomic.AddInt32(&s.open, 1)
  1623. if !wp.Serve(c) {
  1624. atomic.AddInt32(&s.open, -1)
  1625. atomic.AddUint32(&s.rejectedRequestsCount, 1)
  1626. s.writeFastError(c, StatusServiceUnavailable,
  1627. "The connection cannot be served because Server.Concurrency limit exceeded")
  1628. c.Close()
  1629. s.setState(c, StateClosed)
  1630. if time.Since(lastOverflowErrorTime) > time.Minute {
  1631. s.logger().Printf("The incoming connection cannot be served, because %d concurrent connections are served. "+
  1632. "Try increasing Server.Concurrency", maxWorkersCount)
  1633. lastOverflowErrorTime = time.Now()
  1634. }
  1635. // The current server reached concurrency limit,
  1636. // so give other concurrently running servers a chance
  1637. // accepting incoming connections on the same address.
  1638. //
  1639. // There is a hope other servers didn't reach their
  1640. // concurrency limits yet :)
  1641. //
  1642. // See also: https://github.com/valyala/fasthttp/pull/485#discussion_r239994990
  1643. if s.SleepWhenConcurrencyLimitsExceeded > 0 {
  1644. time.Sleep(s.SleepWhenConcurrencyLimitsExceeded)
  1645. }
  1646. }
  1647. }
  1648. }
  1649. // Shutdown gracefully shuts down the server without interrupting any active connections.
  1650. // Shutdown works by first closing all open listeners and then waiting indefinitely for all connections
  1651. // to return to idle and then shut down.
  1652. //
  1653. // When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return nil.
  1654. // Make sure the program doesn't exit and waits instead for Shutdown to return.
  1655. //
  1656. // Shutdown does not close keepalive connections so it's recommended to set ReadTimeout and IdleTimeout to something else than 0.
  1657. func (s *Server) Shutdown() error {
  1658. return s.ShutdownWithContext(context.Background())
  1659. }
  1660. // ShutdownWithContext gracefully shuts down the server without interrupting any active connections.
  1661. // ShutdownWithContext works by first closing all open listeners and then waiting for all connections to return to idle
  1662. // or context timeout and then shut down.
  1663. //
  1664. // When ShutdownWithContext is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return nil.
  1665. // Make sure the program doesn't exit and waits instead for Shutdown to return.
  1666. //
  1667. // ShutdownWithContext does not close keepalive connections so it's recommended to set ReadTimeout and IdleTimeout
  1668. // to something else than 0.
  1669. //
  1670. // When ShutdownWithContext returns errors, any operation to the Server is unavailable.
  1671. func (s *Server) ShutdownWithContext(ctx context.Context) (err error) {
  1672. s.mu.Lock()
  1673. defer s.mu.Unlock()
  1674. atomic.StoreInt32(&s.stop, 1)
  1675. defer atomic.StoreInt32(&s.stop, 0)
  1676. if s.ln == nil {
  1677. return nil
  1678. }
  1679. lnerr := s.closeListenersLocked()
  1680. if s.done != nil {
  1681. close(s.done)
  1682. }
  1683. // Closing the listener will make Serve() call Stop on the worker pool.
  1684. // Setting .stop to 1 will make serveConn() break out of its loop.
  1685. // Now we just have to wait until all workers are done or timeout.
  1686. ticker := time.NewTicker(time.Millisecond * 100)
  1687. defer ticker.Stop()
  1688. for {
  1689. s.closeIdleConns()
  1690. if open := atomic.LoadInt32(&s.open); open == 0 {
  1691. // There may be a pending request to call ctx.Done(). Therefore, we only set it to nil when open == 0.
  1692. s.done = nil
  1693. return lnerr
  1694. }
  1695. // This is not an optimal solution but using a sync.WaitGroup
  1696. // here causes data races as it's hard to prevent Add() to be called
  1697. // while Wait() is waiting.
  1698. select {
  1699. case <-ctx.Done():
  1700. return ctx.Err()
  1701. case <-ticker.C:
  1702. continue
  1703. }
  1704. }
  1705. }
  1706. func acceptConn(s *Server, ln net.Listener, lastPerIPErrorTime *time.Time) (net.Conn, error) {
  1707. for {
  1708. c, err := ln.Accept()
  1709. if err != nil {
  1710. if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
  1711. s.logger().Printf("Timeout error when accepting new connections: %v", netErr)
  1712. time.Sleep(time.Second)
  1713. continue
  1714. }
  1715. if err != io.EOF && !strings.Contains(err.Error(), "use of closed network connection") {
  1716. s.logger().Printf("Permanent error when accepting new connections: %v", err)
  1717. return nil, err
  1718. }
  1719. return nil, io.EOF
  1720. }
  1721. if tc, ok := c.(*net.TCPConn); ok && s.TCPKeepalive {
  1722. if err := tc.SetKeepAlive(s.TCPKeepalive); err != nil {
  1723. _ = tc.Close()
  1724. return nil, err
  1725. }
  1726. if s.TCPKeepalivePeriod > 0 {
  1727. if err := tc.SetKeepAlivePeriod(s.TCPKeepalivePeriod); err != nil {
  1728. _ = tc.Close()
  1729. return nil, err
  1730. }
  1731. }
  1732. }
  1733. if s.MaxConnsPerIP > 0 {
  1734. pic := wrapPerIPConn(s, c)
  1735. if pic == nil {
  1736. if time.Since(*lastPerIPErrorTime) > time.Minute {
  1737. s.logger().Printf("The number of connections from %s exceeds MaxConnsPerIP=%d",
  1738. getConnIP4(c), s.MaxConnsPerIP)
  1739. *lastPerIPErrorTime = time.Now()
  1740. }
  1741. continue
  1742. }
  1743. c = pic
  1744. }
  1745. return c, nil
  1746. }
  1747. }
  1748. func wrapPerIPConn(s *Server, c net.Conn) net.Conn {
  1749. ip := getUint32IP(c)
  1750. if ip == 0 {
  1751. return c
  1752. }
  1753. n := s.perIPConnCounter.Register(ip)
  1754. if n > s.MaxConnsPerIP {
  1755. s.perIPConnCounter.Unregister(ip)
  1756. s.writeFastError(c, StatusTooManyRequests, "The number of connections from your ip exceeds MaxConnsPerIP")
  1757. c.Close()
  1758. return nil
  1759. }
  1760. return acquirePerIPConn(c, ip, &s.perIPConnCounter)
  1761. }
  1762. var defaultLogger = Logger(log.New(os.Stderr, "", log.LstdFlags))
  1763. func (s *Server) logger() Logger {
  1764. if s.Logger != nil {
  1765. return s.Logger
  1766. }
  1767. return defaultLogger
  1768. }
  1769. var (
  1770. // ErrPerIPConnLimit may be returned from ServeConn if the number of connections
  1771. // per ip exceeds Server.MaxConnsPerIP.
  1772. ErrPerIPConnLimit = errors.New("too many connections per ip")
  1773. // ErrConcurrencyLimit may be returned from ServeConn if the number
  1774. // of concurrently served connections exceeds Server.Concurrency.
  1775. ErrConcurrencyLimit = errors.New("cannot serve the connection because Server.Concurrency concurrent connections are served")
  1776. )
  1777. // ServeConn serves HTTP requests from the given connection.
  1778. //
  1779. // ServeConn returns nil if all requests from the c are successfully served.
  1780. // It returns non-nil error otherwise.
  1781. //
  1782. // Connection c must immediately propagate all the data passed to Write()
  1783. // to the client. Otherwise requests' processing may hang.
  1784. //
  1785. // ServeConn closes c before returning.
  1786. func (s *Server) ServeConn(c net.Conn) error {
  1787. if s.MaxConnsPerIP > 0 {
  1788. pic := wrapPerIPConn(s, c)
  1789. if pic == nil {
  1790. return ErrPerIPConnLimit
  1791. }
  1792. c = pic
  1793. }
  1794. n := int(atomic.AddUint32(&s.concurrency, 1)) // #nosec G115
  1795. if n > s.getConcurrency() {
  1796. atomic.AddUint32(&s.concurrency, ^uint32(0))
  1797. s.writeFastError(c, StatusServiceUnavailable, "The connection cannot be served because Server.Concurrency limit exceeded")
  1798. c.Close()
  1799. return ErrConcurrencyLimit
  1800. }
  1801. atomic.AddInt32(&s.open, 1)
  1802. err := s.serveConn(c)
  1803. atomic.AddUint32(&s.concurrency, ^uint32(0))
  1804. if err != errHijacked {
  1805. errc := c.Close()
  1806. s.setState(c, StateClosed)
  1807. if err == nil {
  1808. err = errc
  1809. }
  1810. } else {
  1811. err = nil
  1812. s.setState(c, StateHijacked)
  1813. }
  1814. return err
  1815. }
  1816. var errHijacked = errors.New("connection has been hijacked")
  1817. // GetCurrentConcurrency returns a number of currently served
  1818. // connections.
  1819. //
  1820. // This function is intended be used by monitoring systems.
  1821. func (s *Server) GetCurrentConcurrency() uint32 {
  1822. return atomic.LoadUint32(&s.concurrency)
  1823. }
  1824. // GetOpenConnectionsCount returns a number of opened connections.
  1825. //
  1826. // This function is intended be used by monitoring systems.
  1827. func (s *Server) GetOpenConnectionsCount() int32 {
  1828. if atomic.LoadInt32(&s.stop) == 0 {
  1829. // Decrement by one to avoid reporting the extra open value that gets
  1830. // counted while the server is listening.
  1831. return atomic.LoadInt32(&s.open) - 1
  1832. }
  1833. // This is not perfect, because s.stop could have changed to zero
  1834. // before we load the value of s.open. However, in the common case
  1835. // this avoids underreporting open connections by 1 during server shutdown.
  1836. return atomic.LoadInt32(&s.open)
  1837. }
  1838. // GetRejectedConnectionsCount returns a number of rejected connections.
  1839. //
  1840. // This function is intended be used by monitoring systems.
  1841. func (s *Server) GetRejectedConnectionsCount() uint32 {
  1842. return atomic.LoadUint32(&s.rejectedRequestsCount)
  1843. }
  1844. func (s *Server) getConcurrency() int {
  1845. n := s.Concurrency
  1846. if n <= 0 {
  1847. n = DefaultConcurrency
  1848. }
  1849. return n
  1850. }
  1851. var globalConnID uint64
  1852. func nextConnID() uint64 {
  1853. return atomic.AddUint64(&globalConnID, 1)
  1854. }
  1855. // DefaultMaxRequestBodySize is the maximum request body size the server
  1856. // reads by default.
  1857. //
  1858. // See Server.MaxRequestBodySize for details.
  1859. const DefaultMaxRequestBodySize = 4 * 1024 * 1024
  1860. func (s *Server) idleTimeout() time.Duration {
  1861. if s.IdleTimeout != 0 {
  1862. return s.IdleTimeout
  1863. }
  1864. return s.ReadTimeout
  1865. }
  1866. func (s *Server) serveConnCleanup() {
  1867. atomic.AddInt32(&s.open, -1)
  1868. atomic.AddUint32(&s.concurrency, ^uint32(0))
  1869. }
  1870. func (s *Server) serveConn(c net.Conn) (err error) {
  1871. defer s.serveConnCleanup()
  1872. atomic.AddUint32(&s.concurrency, 1)
  1873. var proto string
  1874. if proto, err = s.getNextProto(c); err != nil {
  1875. return
  1876. }
  1877. if handler, ok := s.nextProtos[proto]; ok {
  1878. // Remove read or write deadlines that might have previously been set.
  1879. // The next handler is responsible for setting its own deadlines.
  1880. if s.ReadTimeout > 0 || s.WriteTimeout > 0 {
  1881. if err = c.SetDeadline(zeroTime); err != nil {
  1882. return
  1883. }
  1884. }
  1885. return handler(c)
  1886. }
  1887. serverName := s.getServerName()
  1888. connRequestNum := uint64(0)
  1889. connID := nextConnID()
  1890. connTime := time.Now()
  1891. maxRequestBodySize := s.MaxRequestBodySize
  1892. if maxRequestBodySize <= 0 {
  1893. maxRequestBodySize = DefaultMaxRequestBodySize
  1894. }
  1895. writeTimeout := s.WriteTimeout
  1896. previousWriteTimeout := time.Duration(0)
  1897. ctx := s.acquireCtx(c)
  1898. ctx.connTime = connTime
  1899. isTLS := ctx.IsTLS()
  1900. var (
  1901. br *bufio.Reader
  1902. bw *bufio.Writer
  1903. timeoutResponse *Response
  1904. hijackHandler HijackHandler
  1905. hijackNoResponse bool
  1906. connectionClose bool
  1907. continueReadingRequest = true
  1908. )
  1909. for {
  1910. connRequestNum++
  1911. // If this is a keep-alive connection set the idle timeout.
  1912. if connRequestNum > 1 {
  1913. if d := s.idleTimeout(); d > 0 {
  1914. if err = c.SetReadDeadline(time.Now().Add(d)); err != nil {
  1915. break
  1916. }
  1917. }
  1918. }
  1919. if !s.ReduceMemoryUsage || br != nil {
  1920. if br == nil {
  1921. br = acquireReader(ctx)
  1922. }
  1923. // If this is a keep-alive connection we want to try and read the first bytes
  1924. // within the idle time.
  1925. if connRequestNum > 1 {
  1926. var b []byte
  1927. b, err = br.Peek(1)
  1928. if len(b) == 0 {
  1929. // If reading from a keep-alive connection returns nothing it means
  1930. // the connection was closed (either timeout or from the other side).
  1931. if err != io.EOF {
  1932. err = ErrNothingRead{error: err}
  1933. }
  1934. }
  1935. }
  1936. } else {
  1937. // If this is a keep-alive connection acquireByteReader will try to peek
  1938. // a couple of bytes already so the idle timeout will already be used.
  1939. br, err = acquireByteReader(&ctx)
  1940. }
  1941. ctx.Request.isTLS = isTLS
  1942. ctx.Response.Header.noDefaultContentType = s.NoDefaultContentType
  1943. ctx.Response.Header.noDefaultDate = s.NoDefaultDate
  1944. // Secure header error logs configuration
  1945. ctx.Request.Header.secureErrorLogMessage = s.SecureErrorLogMessage
  1946. ctx.Response.Header.secureErrorLogMessage = s.SecureErrorLogMessage
  1947. ctx.Request.secureErrorLogMessage = s.SecureErrorLogMessage
  1948. ctx.Response.secureErrorLogMessage = s.SecureErrorLogMessage
  1949. if err == nil {
  1950. s.setState(c, StateActive)
  1951. if s.ReadTimeout > 0 {
  1952. if err = c.SetReadDeadline(time.Now().Add(s.ReadTimeout)); err != nil {
  1953. break
  1954. }
  1955. } else if s.IdleTimeout > 0 && connRequestNum > 1 {
  1956. // If this was an idle connection and the server has an IdleTimeout but
  1957. // no ReadTimeout then we should remove the ReadTimeout.
  1958. if err = c.SetReadDeadline(zeroTime); err != nil {
  1959. break
  1960. }
  1961. }
  1962. if s.DisableHeaderNamesNormalizing {
  1963. ctx.Request.Header.DisableNormalizing()
  1964. ctx.Response.Header.DisableNormalizing()
  1965. }
  1966. // Reading Headers.
  1967. //
  1968. // If we have pipeline response in the outgoing buffer,
  1969. // we only want to try and read the next headers once.
  1970. // If we have to wait for the next request we flush the
  1971. // outgoing buffer first so it doesn't have to wait.
  1972. if bw != nil && bw.Buffered() > 0 {
  1973. err = ctx.Request.Header.readLoop(br, false)
  1974. if err == errNeedMore {
  1975. err = bw.Flush()
  1976. if err != nil {
  1977. break
  1978. }
  1979. err = ctx.Request.Header.Read(br)
  1980. }
  1981. } else {
  1982. err = ctx.Request.Header.Read(br)
  1983. }
  1984. if err == nil {
  1985. if onHdrRecv := s.HeaderReceived; onHdrRecv != nil {
  1986. reqConf := onHdrRecv(&ctx.Request.Header)
  1987. if reqConf.ReadTimeout > 0 {
  1988. deadline := time.Now().Add(reqConf.ReadTimeout)
  1989. if err = c.SetReadDeadline(deadline); err != nil {
  1990. break
  1991. }
  1992. }
  1993. switch {
  1994. case reqConf.MaxRequestBodySize > 0:
  1995. maxRequestBodySize = reqConf.MaxRequestBodySize
  1996. case s.MaxRequestBodySize > 0:
  1997. maxRequestBodySize = s.MaxRequestBodySize
  1998. default:
  1999. maxRequestBodySize = DefaultMaxRequestBodySize
  2000. }
  2001. if reqConf.WriteTimeout > 0 {
  2002. writeTimeout = reqConf.WriteTimeout
  2003. } else {
  2004. writeTimeout = s.WriteTimeout
  2005. }
  2006. }
  2007. // read body
  2008. if s.StreamRequestBody {
  2009. err = ctx.Request.readBodyStream(br, maxRequestBodySize, s.GetOnly, !s.DisablePreParseMultipartForm)
  2010. } else {
  2011. err = ctx.Request.readLimitBody(br, maxRequestBodySize, s.GetOnly, !s.DisablePreParseMultipartForm)
  2012. }
  2013. }
  2014. // When StreamRequestBody is set to true, we cannot safely release br.
  2015. // For example, when using chunked encoding, it's possible that br has only read the request headers.
  2016. if (!s.StreamRequestBody && s.ReduceMemoryUsage && br.Buffered() == 0) || err != nil {
  2017. releaseReader(s, br)
  2018. br = nil
  2019. }
  2020. }
  2021. if err != nil {
  2022. if err == io.EOF {
  2023. err = nil
  2024. } else if nr, ok := err.(ErrNothingRead); ok {
  2025. if connRequestNum > 1 {
  2026. // This is not the first request and we haven't read a single byte
  2027. // of a new request yet. This means it's just a keep-alive connection
  2028. // closing down either because the remote closed it or because
  2029. // or a read timeout on our side. Either way just close the connection
  2030. // and don't return any error response.
  2031. err = nil
  2032. } else {
  2033. err = nr.error
  2034. }
  2035. }
  2036. if err != nil {
  2037. bw = s.writeErrorResponse(bw, ctx, serverName, err)
  2038. }
  2039. break
  2040. }
  2041. // 'Expect: 100-continue' request handling.
  2042. // See https://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3 for details.
  2043. if ctx.Request.MayContinue() {
  2044. // Allow the ability to deny reading the incoming request body
  2045. if s.ContinueHandler != nil {
  2046. if continueReadingRequest = s.ContinueHandler(&ctx.Request.Header); !continueReadingRequest {
  2047. if br != nil {
  2048. br.Reset(ctx.c)
  2049. }
  2050. ctx.SetStatusCode(StatusExpectationFailed)
  2051. }
  2052. }
  2053. if continueReadingRequest {
  2054. if bw == nil {
  2055. bw = acquireWriter(ctx)
  2056. }
  2057. // Send 'HTTP/1.1 100 Continue' response.
  2058. _, err = bw.Write(strResponseContinue)
  2059. if err != nil {
  2060. break
  2061. }
  2062. err = bw.Flush()
  2063. if err != nil {
  2064. break
  2065. }
  2066. if s.ReduceMemoryUsage {
  2067. releaseWriter(s, bw)
  2068. bw = nil
  2069. }
  2070. // Read request body.
  2071. if br == nil {
  2072. br = acquireReader(ctx)
  2073. }
  2074. if s.StreamRequestBody {
  2075. err = ctx.Request.ContinueReadBodyStream(br, maxRequestBodySize, !s.DisablePreParseMultipartForm)
  2076. } else {
  2077. err = ctx.Request.ContinueReadBody(br, maxRequestBodySize, !s.DisablePreParseMultipartForm)
  2078. }
  2079. if (!s.StreamRequestBody && s.ReduceMemoryUsage && br.Buffered() == 0) || err != nil {
  2080. releaseReader(s, br)
  2081. br = nil
  2082. }
  2083. if err != nil {
  2084. bw = s.writeErrorResponse(bw, ctx, serverName, err)
  2085. break
  2086. }
  2087. }
  2088. }
  2089. // store req.ConnectionClose so even if it was changed inside of handler
  2090. connectionClose = s.DisableKeepalive || ctx.Request.Header.ConnectionClose()
  2091. if serverName != "" {
  2092. ctx.Response.Header.SetServer(serverName)
  2093. }
  2094. ctx.connID = connID
  2095. ctx.connRequestNum = connRequestNum
  2096. ctx.time = time.Now()
  2097. // If a client denies a request the handler should not be called
  2098. if continueReadingRequest {
  2099. s.Handler(ctx)
  2100. }
  2101. timeoutResponse = ctx.timeoutResponse
  2102. if timeoutResponse != nil {
  2103. // Acquire a new ctx because the old one will still be in use by the timeout out handler.
  2104. ctx = s.acquireCtx(c)
  2105. timeoutResponse.CopyTo(&ctx.Response)
  2106. }
  2107. if ctx.IsHead() {
  2108. ctx.Response.SkipBody = true
  2109. }
  2110. hijackHandler = ctx.hijackHandler
  2111. ctx.hijackHandler = nil
  2112. hijackNoResponse = ctx.hijackNoResponse && hijackHandler != nil
  2113. ctx.hijackNoResponse = false
  2114. if writeTimeout > 0 {
  2115. if err = c.SetWriteDeadline(time.Now().Add(writeTimeout)); err != nil {
  2116. break
  2117. }
  2118. previousWriteTimeout = writeTimeout
  2119. } else if previousWriteTimeout > 0 {
  2120. // We don't want a write timeout but we previously set one, remove it.
  2121. if err = c.SetWriteDeadline(zeroTime); err != nil {
  2122. break
  2123. }
  2124. previousWriteTimeout = 0
  2125. }
  2126. connectionClose = connectionClose ||
  2127. (s.MaxRequestsPerConn > 0 && connRequestNum >= uint64(s.MaxRequestsPerConn)) || // #nosec G115
  2128. ctx.Response.Header.ConnectionClose() ||
  2129. (s.CloseOnShutdown && atomic.LoadInt32(&s.stop) == 1)
  2130. if connectionClose {
  2131. ctx.Response.Header.SetConnectionClose()
  2132. } else if !ctx.Request.Header.IsHTTP11() {
  2133. // Set 'Connection: keep-alive' response header for HTTP/1.0 request.
  2134. // There is no need in setting this header for http/1.1, since in http/1.1
  2135. // connections are keep-alive by default.
  2136. ctx.Response.Header.setNonSpecial(strConnection, strKeepAlive)
  2137. }
  2138. if serverName != "" && len(ctx.Response.Header.Server()) == 0 {
  2139. ctx.Response.Header.SetServer(serverName)
  2140. }
  2141. if !hijackNoResponse {
  2142. if bw == nil {
  2143. bw = acquireWriter(ctx)
  2144. }
  2145. if err = writeResponse(ctx, bw); err != nil {
  2146. break
  2147. }
  2148. // Only flush the writer if we don't have another request in the pipeline.
  2149. // This is a big of an ugly optimization for https://www.techempower.com/benchmarks/
  2150. // This benchmark will send 16 pipelined requests. It is faster to pack as many responses
  2151. // in a TCP packet and send it back at once than waiting for a flush every request.
  2152. // In real world circumstances this behaviour could be argued as being wrong.
  2153. if br == nil || br.Buffered() == 0 || connectionClose || (s.ReduceMemoryUsage && hijackHandler == nil) {
  2154. err = bw.Flush()
  2155. if err != nil {
  2156. break
  2157. }
  2158. }
  2159. if connectionClose {
  2160. break
  2161. }
  2162. if s.ReduceMemoryUsage && hijackHandler == nil {
  2163. releaseWriter(s, bw)
  2164. bw = nil
  2165. }
  2166. }
  2167. if hijackHandler != nil {
  2168. var hjr io.Reader = c
  2169. if br != nil {
  2170. hjr = br
  2171. br = nil
  2172. }
  2173. if bw != nil {
  2174. err = bw.Flush()
  2175. if err != nil {
  2176. break
  2177. }
  2178. releaseWriter(s, bw)
  2179. bw = nil
  2180. }
  2181. err = c.SetDeadline(zeroTime)
  2182. if err != nil {
  2183. break
  2184. }
  2185. go hijackConnHandler(ctx, hjr, c, s, hijackHandler)
  2186. err = errHijacked
  2187. break
  2188. }
  2189. if ctx.Request.bodyStream != nil {
  2190. if rs, ok := ctx.Request.bodyStream.(*requestStream); ok {
  2191. releaseRequestStream(rs)
  2192. }
  2193. ctx.Request.bodyStream = nil
  2194. }
  2195. s.setState(c, StateIdle)
  2196. ctx.userValues.Reset()
  2197. ctx.Request.Reset()
  2198. ctx.Response.Reset()
  2199. if atomic.LoadInt32(&s.stop) == 1 {
  2200. err = nil
  2201. break
  2202. }
  2203. }
  2204. if br != nil {
  2205. releaseReader(s, br)
  2206. }
  2207. if bw != nil {
  2208. releaseWriter(s, bw)
  2209. }
  2210. if hijackHandler == nil {
  2211. s.releaseCtx(ctx)
  2212. }
  2213. return
  2214. }
  2215. func (s *Server) setState(nc net.Conn, state ConnState) {
  2216. s.trackConn(nc, state)
  2217. if hook := s.ConnState; hook != nil {
  2218. hook(nc, state)
  2219. }
  2220. }
  2221. func hijackConnHandler(ctx *RequestCtx, r io.Reader, c net.Conn, s *Server, h HijackHandler) {
  2222. hjc := s.acquireHijackConn(r, c)
  2223. h(hjc)
  2224. if br, ok := r.(*bufio.Reader); ok {
  2225. releaseReader(s, br)
  2226. }
  2227. if !s.KeepHijackedConns {
  2228. c.Close()
  2229. s.releaseHijackConn(hjc)
  2230. }
  2231. s.releaseCtx(ctx)
  2232. }
  2233. func (s *Server) acquireHijackConn(r io.Reader, c net.Conn) *hijackConn {
  2234. v := s.hijackConnPool.Get()
  2235. if v == nil {
  2236. hjc := &hijackConn{
  2237. Conn: c,
  2238. r: r,
  2239. s: s,
  2240. }
  2241. return hjc
  2242. }
  2243. hjc := v.(*hijackConn)
  2244. hjc.Conn = c
  2245. hjc.r = r
  2246. return hjc
  2247. }
  2248. func (s *Server) releaseHijackConn(hjc *hijackConn) {
  2249. hjc.Conn = nil
  2250. hjc.r = nil
  2251. s.hijackConnPool.Put(hjc)
  2252. }
  2253. type hijackConn struct {
  2254. net.Conn
  2255. r io.Reader
  2256. s *Server
  2257. }
  2258. func (c *hijackConn) UnsafeConn() net.Conn {
  2259. return c.Conn
  2260. }
  2261. func (c *hijackConn) Read(p []byte) (int, error) {
  2262. return c.r.Read(p)
  2263. }
  2264. func (c *hijackConn) Close() error {
  2265. if !c.s.KeepHijackedConns {
  2266. // when we do not keep hijacked connections,
  2267. // it is closed in hijackConnHandler.
  2268. return nil
  2269. }
  2270. return c.Conn.Close()
  2271. }
  2272. // LastTimeoutErrorResponse returns the last timeout response set
  2273. // via TimeoutError* call.
  2274. //
  2275. // This function is intended for custom server implementations.
  2276. func (ctx *RequestCtx) LastTimeoutErrorResponse() *Response {
  2277. return ctx.timeoutResponse
  2278. }
  2279. func writeResponse(ctx *RequestCtx, w *bufio.Writer) error {
  2280. if ctx.timeoutResponse != nil {
  2281. return errors.New("cannot write timed out response")
  2282. }
  2283. err := ctx.Response.Write(w)
  2284. return err
  2285. }
  2286. const (
  2287. defaultReadBufferSize = 4096
  2288. defaultWriteBufferSize = 4096
  2289. )
  2290. func acquireByteReader(ctxP **RequestCtx) (*bufio.Reader, error) {
  2291. ctx := *ctxP
  2292. s := ctx.s
  2293. c := ctx.c
  2294. s.releaseCtx(ctx)
  2295. //nolint:wastedassign // Make GC happy, so it could garbage collect ctx while we wait for the
  2296. // next request.
  2297. ctx = nil
  2298. *ctxP = nil
  2299. var b [1]byte
  2300. n, err := c.Read(b[:])
  2301. ctx = s.acquireCtx(c)
  2302. *ctxP = ctx
  2303. if err != nil {
  2304. // Treat all errors as EOF on unsuccessful read
  2305. // of the first request byte.
  2306. return nil, io.EOF
  2307. }
  2308. if n != 1 {
  2309. // developer sanity-check
  2310. panic("BUG: Reader must return at least one byte")
  2311. }
  2312. ctx.fbr.c = c
  2313. ctx.fbr.ch = b[0]
  2314. ctx.fbr.byteRead = false
  2315. r := acquireReader(ctx)
  2316. r.Reset(&ctx.fbr)
  2317. return r, nil
  2318. }
  2319. func acquireReader(ctx *RequestCtx) *bufio.Reader {
  2320. v := ctx.s.readerPool.Get()
  2321. if v == nil {
  2322. n := ctx.s.ReadBufferSize
  2323. if n <= 0 {
  2324. n = defaultReadBufferSize
  2325. }
  2326. return bufio.NewReaderSize(ctx.c, n)
  2327. }
  2328. r := v.(*bufio.Reader)
  2329. r.Reset(ctx.c)
  2330. return r
  2331. }
  2332. func releaseReader(s *Server, r *bufio.Reader) {
  2333. s.readerPool.Put(r)
  2334. }
  2335. func acquireWriter(ctx *RequestCtx) *bufio.Writer {
  2336. v := ctx.s.writerPool.Get()
  2337. if v == nil {
  2338. n := ctx.s.WriteBufferSize
  2339. if n <= 0 {
  2340. n = defaultWriteBufferSize
  2341. }
  2342. return bufio.NewWriterSize(ctx.c, n)
  2343. }
  2344. w := v.(*bufio.Writer)
  2345. w.Reset(ctx.c)
  2346. return w
  2347. }
  2348. func releaseWriter(s *Server, w *bufio.Writer) {
  2349. s.writerPool.Put(w)
  2350. }
  2351. func (s *Server) acquireCtx(c net.Conn) (ctx *RequestCtx) {
  2352. v := s.ctxPool.Get()
  2353. if v == nil {
  2354. keepBodyBuffer := !s.ReduceMemoryUsage
  2355. ctx = new(RequestCtx)
  2356. ctx.Request.keepBodyBuffer = keepBodyBuffer
  2357. ctx.Response.keepBodyBuffer = keepBodyBuffer
  2358. ctx.s = s
  2359. } else {
  2360. ctx = v.(*RequestCtx)
  2361. }
  2362. if s.FormValueFunc != nil {
  2363. ctx.formValueFunc = s.FormValueFunc
  2364. }
  2365. ctx.c = c
  2366. return ctx
  2367. }
  2368. // Init2 prepares ctx for passing to RequestHandler.
  2369. //
  2370. // conn is used only for determining local and remote addresses.
  2371. //
  2372. // This function is intended for custom Server implementations.
  2373. // See https://github.com/valyala/httpteleport for details.
  2374. func (ctx *RequestCtx) Init2(conn net.Conn, logger Logger, reduceMemoryUsage bool) {
  2375. ctx.c = conn
  2376. ctx.remoteAddr = nil
  2377. ctx.logger.logger = logger
  2378. ctx.connID = nextConnID()
  2379. ctx.s = fakeServer
  2380. ctx.connRequestNum = 0
  2381. ctx.connTime = time.Now()
  2382. keepBodyBuffer := !reduceMemoryUsage
  2383. ctx.Request.keepBodyBuffer = keepBodyBuffer
  2384. ctx.Response.keepBodyBuffer = keepBodyBuffer
  2385. }
  2386. // Init prepares ctx for passing to RequestHandler.
  2387. //
  2388. // remoteAddr and logger are optional. They are used by RequestCtx.Logger().
  2389. //
  2390. // This function is intended for custom Server implementations.
  2391. func (ctx *RequestCtx) Init(req *Request, remoteAddr net.Addr, logger Logger) {
  2392. if remoteAddr == nil {
  2393. remoteAddr = zeroTCPAddr
  2394. }
  2395. c := &fakeAddrer{
  2396. laddr: zeroTCPAddr,
  2397. raddr: remoteAddr,
  2398. }
  2399. if logger == nil {
  2400. logger = defaultLogger
  2401. }
  2402. ctx.Init2(c, logger, true)
  2403. req.CopyTo(&ctx.Request)
  2404. }
  2405. // Deadline returns the time when work done on behalf of this context
  2406. // should be canceled. Deadline returns ok==false when no deadline is
  2407. // set. Successive calls to Deadline return the same results.
  2408. //
  2409. // This method always returns 0, false and is only present to make
  2410. // RequestCtx implement the context interface.
  2411. func (ctx *RequestCtx) Deadline() (deadline time.Time, ok bool) {
  2412. return
  2413. }
  2414. // Done returns a channel that's closed when work done on behalf of this
  2415. // context should be canceled. Done may return nil if this context can
  2416. // never be canceled. Successive calls to Done return the same value.
  2417. //
  2418. // Note: Because creating a new channel for every request is just too expensive, so
  2419. // RequestCtx.s.done is only closed when the server is shutting down.
  2420. func (ctx *RequestCtx) Done() <-chan struct{} {
  2421. return ctx.s.done
  2422. }
  2423. // Err returns a non-nil error value after Done is closed,
  2424. // successive calls to Err return the same error.
  2425. // If Done is not yet closed, Err returns nil.
  2426. // If Done is closed, Err returns a non-nil error explaining why:
  2427. // Canceled if the context was canceled (via server Shutdown)
  2428. // or DeadlineExceeded if the context's deadline passed.
  2429. //
  2430. // Note: Because creating a new channel for every request is just too expensive, so
  2431. // RequestCtx.s.done is only closed when the server is shutting down.
  2432. func (ctx *RequestCtx) Err() error {
  2433. select {
  2434. case <-ctx.Done():
  2435. return context.Canceled
  2436. default:
  2437. return nil
  2438. }
  2439. }
  2440. // Value returns the value associated with this context for key, or nil
  2441. // if no value is associated with key. Successive calls to Value with
  2442. // the same key returns the same result.
  2443. //
  2444. // This method is present to make RequestCtx implement the context interface.
  2445. // This method is the same as calling ctx.UserValue(key).
  2446. func (ctx *RequestCtx) Value(key any) any {
  2447. return ctx.UserValue(key)
  2448. }
  2449. var fakeServer = &Server{
  2450. done: make(chan struct{}),
  2451. // Initialize concurrencyCh for TimeoutHandler
  2452. concurrencyCh: make(chan struct{}, DefaultConcurrency),
  2453. }
  2454. type fakeAddrer struct {
  2455. net.Conn
  2456. laddr net.Addr
  2457. raddr net.Addr
  2458. }
  2459. func (fa *fakeAddrer) RemoteAddr() net.Addr {
  2460. return fa.raddr
  2461. }
  2462. func (fa *fakeAddrer) LocalAddr() net.Addr {
  2463. return fa.laddr
  2464. }
  2465. func (fa *fakeAddrer) Read(p []byte) (int, error) {
  2466. // developer sanity-check
  2467. panic("BUG: unexpected Read call")
  2468. }
  2469. func (fa *fakeAddrer) Write(p []byte) (int, error) {
  2470. // developer sanity-check
  2471. panic("BUG: unexpected Write call")
  2472. }
  2473. func (fa *fakeAddrer) Close() error {
  2474. // developer sanity-check
  2475. panic("BUG: unexpected Close call")
  2476. }
  2477. func (s *Server) releaseCtx(ctx *RequestCtx) {
  2478. if ctx.timeoutResponse != nil {
  2479. // developer sanity-check
  2480. panic("BUG: cannot release timed out RequestCtx")
  2481. }
  2482. ctx.reset()
  2483. s.ctxPool.Put(ctx)
  2484. }
  2485. func (s *Server) getServerName() string {
  2486. serverName := s.Name
  2487. if serverName == "" {
  2488. if !s.NoDefaultServerHeader {
  2489. serverName = defaultServerName
  2490. }
  2491. }
  2492. return serverName
  2493. }
  2494. func (s *Server) writeFastError(w io.Writer, statusCode int, msg string) {
  2495. w.Write(formatStatusLine(nil, strHTTP11, statusCode, s2b(StatusMessage(statusCode)))) //nolint:errcheck
  2496. server := s.getServerName()
  2497. if server != "" {
  2498. server = fmt.Sprintf("Server: %s\r\n", server)
  2499. }
  2500. date := ""
  2501. if !s.NoDefaultDate {
  2502. serverDateOnce.Do(updateServerDate)
  2503. date = fmt.Sprintf("Date: %s\r\n", serverDate.Load())
  2504. }
  2505. fmt.Fprintf(w, "Connection: close\r\n"+
  2506. server+
  2507. date+
  2508. "Content-Type: text/plain\r\n"+
  2509. "Content-Length: %d\r\n"+
  2510. "\r\n"+
  2511. "%s",
  2512. len(msg), msg)
  2513. }
  2514. func defaultErrorHandler(ctx *RequestCtx, err error) {
  2515. if _, ok := err.(*ErrSmallBuffer); ok {
  2516. ctx.Error("Too big request header", StatusRequestHeaderFieldsTooLarge)
  2517. } else if netErr, ok := err.(*net.OpError); ok && netErr.Timeout() {
  2518. ctx.Error("Request timeout", StatusRequestTimeout)
  2519. } else {
  2520. ctx.Error("Error when parsing request", StatusBadRequest)
  2521. }
  2522. }
  2523. func (s *Server) writeErrorResponse(bw *bufio.Writer, ctx *RequestCtx, serverName string, err error) *bufio.Writer {
  2524. errorHandler := defaultErrorHandler
  2525. if s.ErrorHandler != nil {
  2526. errorHandler = s.ErrorHandler
  2527. }
  2528. errorHandler(ctx, err)
  2529. if serverName != "" {
  2530. ctx.Response.Header.SetServer(serverName)
  2531. }
  2532. ctx.SetConnectionClose()
  2533. if bw == nil {
  2534. bw = acquireWriter(ctx)
  2535. }
  2536. writeResponse(ctx, bw) //nolint:errcheck
  2537. ctx.Response.Reset()
  2538. bw.Flush()
  2539. return bw
  2540. }
  2541. func (s *Server) trackConn(c net.Conn, state ConnState) {
  2542. s.idleConnsMu.Lock()
  2543. switch state {
  2544. case StateIdle:
  2545. if s.idleConns == nil {
  2546. s.idleConns = make(map[net.Conn]time.Time)
  2547. }
  2548. s.idleConns[c] = time.Now()
  2549. case StateNew:
  2550. if s.idleConns == nil {
  2551. s.idleConns = make(map[net.Conn]time.Time)
  2552. }
  2553. // Count the connection as Idle after 5 seconds.
  2554. // Same as net/http.Server:
  2555. // https://github.com/golang/go/blob/85d7bab91d9a3ed1f76842e4328973ea75efef54/src/net/http/server.go#L2834-L2836
  2556. s.idleConns[c] = time.Now().Add(time.Second * 5)
  2557. default:
  2558. delete(s.idleConns, c)
  2559. }
  2560. s.idleConnsMu.Unlock()
  2561. }
  2562. func (s *Server) closeIdleConns() {
  2563. s.idleConnsMu.Lock()
  2564. now := time.Now()
  2565. for c, t := range s.idleConns {
  2566. if now.Sub(t) >= 0 {
  2567. _ = c.Close()
  2568. delete(s.idleConns, c)
  2569. }
  2570. }
  2571. s.idleConnsMu.Unlock()
  2572. }
  2573. func (s *Server) closeListenersLocked() error {
  2574. var err error
  2575. for _, ln := range s.ln {
  2576. if cerr := ln.Close(); cerr != nil && err == nil {
  2577. err = cerr
  2578. }
  2579. }
  2580. s.ln = nil
  2581. return err
  2582. }
  2583. // A ConnState represents the state of a client connection to a server.
  2584. // It's used by the optional Server.ConnState hook.
  2585. type ConnState int
  2586. const (
  2587. // StateNew represents a new connection that is expected to
  2588. // send a request immediately. Connections begin at this
  2589. // state and then transition to either StateActive or
  2590. // StateClosed.
  2591. StateNew ConnState = iota
  2592. // StateActive represents a connection that has read 1 or more
  2593. // bytes of a request. The Server.ConnState hook for
  2594. // StateActive fires before the request has entered a handler
  2595. // and doesn't fire again until the request has been
  2596. // handled. After the request is handled, the state
  2597. // transitions to StateClosed, StateHijacked, or StateIdle.
  2598. // For HTTP/2, StateActive fires on the transition from zero
  2599. // to one active request, and only transitions away once all
  2600. // active requests are complete. That means that ConnState
  2601. // cannot be used to do per-request work; ConnState only notes
  2602. // the overall state of the connection.
  2603. StateActive
  2604. // StateIdle represents a connection that has finished
  2605. // handling a request and is in the keep-alive state, waiting
  2606. // for a new request. Connections transition from StateIdle
  2607. // to either StateActive or StateClosed.
  2608. StateIdle
  2609. // StateHijacked represents a hijacked connection.
  2610. // This is a terminal state. It does not transition to StateClosed.
  2611. StateHijacked
  2612. // StateClosed represents a closed connection.
  2613. // This is a terminal state. Hijacked connections do not
  2614. // transition to StateClosed.
  2615. StateClosed
  2616. )
  2617. var stateName = []string{
  2618. StateNew: "new",
  2619. StateActive: "active",
  2620. StateIdle: "idle",
  2621. StateHijacked: "hijacked",
  2622. StateClosed: "closed",
  2623. }
  2624. func (c ConnState) String() string {
  2625. return stateName[c]
  2626. }