server.go 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061
  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]*atomic.Int64
  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 atomic.Uint32
  273. open atomic.Int32
  274. stop atomic.Int32
  275. rejectedRequestsCount atomic.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. // Incoming request.
  537. //
  538. // Copying Request by value is forbidden. Use pointer to Request instead.
  539. Request Request
  540. connID uint64
  541. connRequestNum uint64
  542. hijackNoResponse bool
  543. }
  544. // EarlyHints allows the server to hint to the browser what resources a page would need
  545. // so the browser can preload them while waiting for the server's full response. Only Link
  546. // headers already written to the response will be transmitted as Early Hints.
  547. //
  548. // This is a HTTP/2+ feature but all browsers will either understand it or safely ignore it.
  549. //
  550. // NOTE: Older HTTP/1.1 non-browser clients may face compatibility issues.
  551. //
  552. // See: https://developer.chrome.com/docs/web-platform/early-hints and
  553. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Link#syntax
  554. //
  555. // Example:
  556. //
  557. // func(ctx *fasthttp.RequestCtx) {
  558. // ctx.Response.Header.Add("Link", "<https://fonts.google.com>; rel=preconnect")
  559. // ctx.EarlyHints()
  560. // time.Sleep(5*time.Second) // some time-consuming task
  561. // ctx.SetStatusCode(fasthttp.StatusOK)
  562. // ctx.SetBody([]byte("<html><head></head><body><h1>Hello from Fasthttp</h1></body></html>"))
  563. // }
  564. func (ctx *RequestCtx) EarlyHints() error {
  565. links := ctx.Response.Header.PeekAll(b2s(strLink))
  566. if len(links) > 0 {
  567. c := acquireWriter(ctx)
  568. defer releaseWriter(ctx.s, c)
  569. _, err := c.Write(strEarlyHints)
  570. if err != nil {
  571. return err
  572. }
  573. for _, l := range links {
  574. if len(l) == 0 {
  575. continue
  576. }
  577. _, err = c.Write(strLink)
  578. if err != nil {
  579. return err
  580. }
  581. _, err = c.Write(strColon)
  582. if err != nil {
  583. return err
  584. }
  585. _, err = c.Write(strSpace)
  586. if err != nil {
  587. return err
  588. }
  589. _, err = c.Write(l)
  590. if err != nil {
  591. return err
  592. }
  593. _, err = c.Write(strCRLF)
  594. if err != nil {
  595. return err
  596. }
  597. }
  598. _, err = c.Write(strCRLF)
  599. if err != nil {
  600. return err
  601. }
  602. err = c.Flush()
  603. if err != nil {
  604. return err
  605. }
  606. }
  607. return nil
  608. }
  609. // HijackHandler must process the hijacked connection c.
  610. //
  611. // If KeepHijackedConns is disabled, which is by default,
  612. // the connection c is automatically closed after returning from HijackHandler.
  613. //
  614. // The connection c must not be used after returning from the handler, if KeepHijackedConns is disabled.
  615. //
  616. // When KeepHijackedConns enabled, fasthttp will not Close() the connection,
  617. // you must do it when you need it. You must not use c in any way after calling Close().
  618. type HijackHandler func(c net.Conn)
  619. // Hijack registers the given handler for connection hijacking.
  620. //
  621. // The handler is called after returning from RequestHandler
  622. // and sending http response. The current connection is passed
  623. // to the handler. The connection is automatically closed after
  624. // returning from the handler.
  625. //
  626. // The server skips calling the handler in the following cases:
  627. //
  628. // - 'Connection: close' header exists in either request or response.
  629. // - Unexpected error during response writing to the connection.
  630. //
  631. // The server stops processing requests from hijacked connections.
  632. //
  633. // Server limits such as Concurrency, ReadTimeout, WriteTimeout, etc.
  634. // aren't applied to hijacked connections.
  635. //
  636. // The handler must not retain references to ctx members.
  637. //
  638. // Arbitrary 'Connection: Upgrade' protocols may be implemented
  639. // with HijackHandler. For instance,
  640. //
  641. // - WebSocket ( https://en.wikipedia.org/wiki/WebSocket )
  642. // - HTTP/2.0 ( https://en.wikipedia.org/wiki/HTTP/2 )
  643. func (ctx *RequestCtx) Hijack(handler HijackHandler) {
  644. ctx.hijackHandler = handler
  645. }
  646. // HijackSetNoResponse changes the behavior of hijacking a request.
  647. // If HijackSetNoResponse is called with false fasthttp will send a response
  648. // to the client before calling the HijackHandler (default). If HijackSetNoResponse
  649. // is called with true no response is send back before calling the
  650. // HijackHandler supplied in the Hijack function.
  651. func (ctx *RequestCtx) HijackSetNoResponse(noResponse bool) {
  652. ctx.hijackNoResponse = noResponse
  653. }
  654. // Hijacked returns true after Hijack is called.
  655. func (ctx *RequestCtx) Hijacked() bool {
  656. return ctx.hijackHandler != nil
  657. }
  658. // SetUserValue stores the given value (arbitrary object)
  659. // under the given key in Request.
  660. //
  661. // The value stored in Request may be obtained by UserValue*.
  662. //
  663. // This functionality may be useful for passing arbitrary values between
  664. // functions involved in request processing.
  665. //
  666. // All the values are removed from Request after returning from the top
  667. // RequestHandler. Additionally, Close method is called on each value
  668. // implementing io.Closer before removing the value from Request.
  669. func (ctx *RequestCtx) SetUserValue(key, value any) {
  670. ctx.Request.SetUserValue(key, value)
  671. }
  672. // SetUserValueBytes stores the given value (arbitrary object)
  673. // under the given key in Request.
  674. //
  675. // The value stored in Request may be obtained by UserValue*.
  676. //
  677. // This functionality may be useful for passing arbitrary values between
  678. // functions involved in request processing.
  679. //
  680. // All the values stored in Request are deleted after returning from RequestHandler.
  681. func (ctx *RequestCtx) SetUserValueBytes(key []byte, value any) {
  682. ctx.Request.SetUserValueBytes(key, value)
  683. }
  684. // UserValue returns the value stored via SetUserValue* under the given key.
  685. func (ctx *RequestCtx) UserValue(key any) any {
  686. return ctx.Request.UserValue(key)
  687. }
  688. // UserValueBytes returns the value stored via SetUserValue*
  689. // under the given key.
  690. func (ctx *RequestCtx) UserValueBytes(key []byte) any {
  691. return ctx.Request.UserValueBytes(key)
  692. }
  693. // VisitUserValues calls visitor for each existing userValue with a key that is a string or []byte.
  694. //
  695. // visitor must not retain references to key and value after returning.
  696. // Make key and/or value copies if you need storing them after returning.
  697. func (ctx *RequestCtx) VisitUserValues(visitor func([]byte, any)) {
  698. ctx.Request.VisitUserValues(visitor)
  699. }
  700. // VisitUserValuesAll calls visitor for each existing userValue.
  701. //
  702. // visitor must not retain references to key and value after returning.
  703. // Make key and/or value copies if you need storing them after returning.
  704. func (ctx *RequestCtx) VisitUserValuesAll(visitor func(any, any)) {
  705. ctx.Request.VisitUserValuesAll(visitor)
  706. }
  707. // ResetUserValues allows to reset user values from Request.
  708. func (ctx *RequestCtx) ResetUserValues() {
  709. ctx.Request.ResetUserValues()
  710. }
  711. // RemoveUserValue removes the given key and the value under it in Request.
  712. func (ctx *RequestCtx) RemoveUserValue(key any) {
  713. ctx.Request.RemoveUserValue(key)
  714. }
  715. // RemoveUserValueBytes removes the given key and the value under it in Request.
  716. func (ctx *RequestCtx) RemoveUserValueBytes(key []byte) {
  717. ctx.Request.RemoveUserValueBytes(key)
  718. }
  719. type connTLSer interface {
  720. Handshake() error
  721. ConnectionState() tls.ConnectionState
  722. }
  723. // IsTLS returns true if the underlying connection is tls.Conn.
  724. //
  725. // tls.Conn is an encrypted connection (aka SSL, HTTPS).
  726. func (ctx *RequestCtx) IsTLS() bool {
  727. // cast to (connTLSer) instead of (*tls.Conn), since it catches
  728. // cases with overridden tls.Conn such as:
  729. //
  730. // type customConn struct {
  731. // *tls.Conn
  732. //
  733. // // other custom fields here
  734. // }
  735. // perIPConn wraps the net.Conn in the Conn field
  736. if pic, ok := ctx.c.(*perIPConn); ok {
  737. _, ok := pic.Conn.(connTLSer)
  738. return ok
  739. }
  740. _, ok := ctx.c.(connTLSer)
  741. return ok
  742. }
  743. // TLSConnectionState returns TLS connection state.
  744. //
  745. // The function returns nil if the underlying connection isn't tls.Conn.
  746. //
  747. // The returned state may be used for verifying TLS version, client certificates,
  748. // etc.
  749. func (ctx *RequestCtx) TLSConnectionState() *tls.ConnectionState {
  750. tlsConn, ok := ctx.c.(connTLSer)
  751. if !ok {
  752. return nil
  753. }
  754. state := tlsConn.ConnectionState()
  755. return &state
  756. }
  757. // Conn returns a reference to the underlying net.Conn.
  758. //
  759. // WARNING: Only use this method if you know what you are doing!
  760. //
  761. // Reading from or writing to the returned connection will end badly!
  762. func (ctx *RequestCtx) Conn() net.Conn {
  763. return ctx.c
  764. }
  765. func (ctx *RequestCtx) reset() {
  766. ctx.Request.Reset()
  767. ctx.Response.Reset()
  768. ctx.fbr.reset()
  769. ctx.connID = 0
  770. ctx.connRequestNum = 0
  771. ctx.connTime = zeroTime
  772. ctx.remoteAddr = nil
  773. ctx.time = zeroTime
  774. ctx.c = nil
  775. // Don't reset ctx.s!
  776. // We have a pool per server so the next time this ctx is used it
  777. // will be assigned the same value again.
  778. // ctx might still be in use for context.Done() and context.Err()
  779. // which are safe to use as they only use ctx.s and no other value.
  780. if ctx.timeoutResponse != nil {
  781. ctx.timeoutResponse.Reset()
  782. }
  783. if ctx.timeoutTimer != nil {
  784. stopTimer(ctx.timeoutTimer)
  785. }
  786. ctx.hijackHandler = nil
  787. ctx.hijackNoResponse = false
  788. }
  789. type firstByteReader struct {
  790. c net.Conn
  791. ch byte
  792. byteRead bool
  793. }
  794. func (r *firstByteReader) reset() {
  795. r.c = nil
  796. r.ch = 0
  797. r.byteRead = false
  798. }
  799. func (r *firstByteReader) Read(b []byte) (int, error) {
  800. if len(b) == 0 {
  801. return 0, nil
  802. }
  803. nn := 0
  804. if !r.byteRead {
  805. b[0] = r.ch
  806. b = b[1:]
  807. r.byteRead = true
  808. nn = 1
  809. }
  810. n, err := r.c.Read(b)
  811. return n + nn, err
  812. }
  813. // Logger is used for logging formatted messages.
  814. type Logger interface {
  815. // Printf must have the same semantics as log.Printf.
  816. Printf(format string, args ...any)
  817. }
  818. var ctxLoggerLock sync.Mutex
  819. type ctxLogger struct {
  820. ctx *RequestCtx
  821. logger Logger
  822. }
  823. func (cl *ctxLogger) Printf(format string, args ...any) {
  824. msg := fmt.Sprintf(format, args...)
  825. ctxLoggerLock.Lock()
  826. cl.logger.Printf("%.3f %s - %s", time.Since(cl.ctx.ConnTime()).Seconds(), cl.ctx.String(), msg)
  827. ctxLoggerLock.Unlock()
  828. }
  829. var zeroTCPAddr = &net.TCPAddr{
  830. IP: net.IPv4zero,
  831. }
  832. // String returns unique string representation of the ctx.
  833. //
  834. // The returned value may be useful for logging.
  835. func (ctx *RequestCtx) String() string {
  836. return fmt.Sprintf("#%016X - %s<->%s - %s %s", ctx.ID(), ctx.LocalAddr(), ctx.RemoteAddr(),
  837. ctx.Request.Header.Method(), ctx.URI().FullURI())
  838. }
  839. // ID returns unique ID of the request.
  840. func (ctx *RequestCtx) ID() uint64 {
  841. return (ctx.connID << 32) | ctx.connRequestNum
  842. }
  843. // ConnID returns unique connection ID.
  844. //
  845. // This ID may be used to match distinct requests to the same incoming
  846. // connection.
  847. func (ctx *RequestCtx) ConnID() uint64 {
  848. return ctx.connID
  849. }
  850. // Time returns RequestHandler call time.
  851. func (ctx *RequestCtx) Time() time.Time {
  852. return ctx.time
  853. }
  854. // ConnTime returns the time the server started serving the connection
  855. // the current request came from.
  856. func (ctx *RequestCtx) ConnTime() time.Time {
  857. return ctx.connTime
  858. }
  859. // ConnRequestNum returns request sequence number
  860. // for the current connection.
  861. //
  862. // Sequence starts with 1.
  863. func (ctx *RequestCtx) ConnRequestNum() uint64 {
  864. return ctx.connRequestNum
  865. }
  866. // SetConnectionClose sets 'Connection: close' response header and closes
  867. // connection after the RequestHandler returns.
  868. func (ctx *RequestCtx) SetConnectionClose() {
  869. ctx.Response.SetConnectionClose()
  870. }
  871. // SetStatusCode sets response status code.
  872. func (ctx *RequestCtx) SetStatusCode(statusCode int) {
  873. ctx.Response.SetStatusCode(statusCode)
  874. }
  875. // SetContentType sets response Content-Type.
  876. func (ctx *RequestCtx) SetContentType(contentType string) {
  877. ctx.Response.Header.SetContentType(contentType)
  878. }
  879. // SetContentTypeBytes sets response Content-Type.
  880. //
  881. // It is safe modifying contentType buffer after function return.
  882. func (ctx *RequestCtx) SetContentTypeBytes(contentType []byte) {
  883. ctx.Response.Header.SetContentTypeBytes(contentType)
  884. }
  885. // RequestURI returns RequestURI.
  886. //
  887. // The returned bytes are valid until your request handler returns.
  888. func (ctx *RequestCtx) RequestURI() []byte {
  889. return ctx.Request.Header.RequestURI()
  890. }
  891. // URI returns requested uri.
  892. //
  893. // This uri is valid until your request handler returns.
  894. func (ctx *RequestCtx) URI() *URI {
  895. return ctx.Request.URI()
  896. }
  897. // Referer returns request referer.
  898. //
  899. // The returned bytes are valid until your request handler returns.
  900. func (ctx *RequestCtx) Referer() []byte {
  901. return ctx.Request.Header.Referer()
  902. }
  903. // UserAgent returns User-Agent header value from the request.
  904. //
  905. // The returned bytes are valid until your request handler returns.
  906. func (ctx *RequestCtx) UserAgent() []byte {
  907. return ctx.Request.Header.UserAgent()
  908. }
  909. // Path returns requested path.
  910. //
  911. // The returned bytes are valid until your request handler returns.
  912. func (ctx *RequestCtx) Path() []byte {
  913. return ctx.URI().Path()
  914. }
  915. // Host returns requested host.
  916. //
  917. // The returned bytes are valid until your request handler returns.
  918. func (ctx *RequestCtx) Host() []byte {
  919. return ctx.URI().Host()
  920. }
  921. // QueryArgs returns query arguments from RequestURI.
  922. //
  923. // It doesn't return POST'ed arguments - use PostArgs() for this.
  924. //
  925. // See also PostArgs, FormValue and FormFile.
  926. //
  927. // These args are valid until your request handler returns.
  928. func (ctx *RequestCtx) QueryArgs() *Args {
  929. return ctx.URI().QueryArgs()
  930. }
  931. // PostArgs returns POST arguments.
  932. //
  933. // It doesn't return query arguments from RequestURI - use QueryArgs for this.
  934. //
  935. // See also QueryArgs, FormValue and FormFile.
  936. //
  937. // These args are valid until your request handler returns.
  938. func (ctx *RequestCtx) PostArgs() *Args {
  939. return ctx.Request.PostArgs()
  940. }
  941. // MultipartForm returns request's multipart form.
  942. //
  943. // Returns ErrNoMultipartForm if request's content-type
  944. // isn't 'multipart/form-data'.
  945. //
  946. // All uploaded temporary files are automatically deleted after
  947. // returning from RequestHandler. Either move or copy uploaded files
  948. // into new place if you want retaining them.
  949. //
  950. // Use SaveMultipartFile function for permanently saving uploaded file.
  951. //
  952. // The returned form is valid until your request handler returns.
  953. //
  954. // See also FormFile and FormValue.
  955. func (ctx *RequestCtx) MultipartForm() (*multipart.Form, error) {
  956. return ctx.Request.MultipartForm()
  957. }
  958. // FormFile returns uploaded file associated with the given multipart form key.
  959. //
  960. // The file is automatically deleted after returning from RequestHandler,
  961. // so either move or copy uploaded file into new place if you want retaining it.
  962. //
  963. // Use SaveMultipartFile function for permanently saving uploaded file.
  964. //
  965. // The returned file header is valid until your request handler returns.
  966. func (ctx *RequestCtx) FormFile(key string) (*multipart.FileHeader, error) {
  967. mf, err := ctx.MultipartForm()
  968. if err != nil {
  969. return nil, err
  970. }
  971. if mf.File == nil {
  972. return nil, err
  973. }
  974. fhh := mf.File[key]
  975. if fhh == nil {
  976. return nil, ErrMissingFile
  977. }
  978. return fhh[0], nil
  979. }
  980. // ErrMissingFile may be returned from FormFile when the is no uploaded file
  981. // associated with the given multipart form key.
  982. var ErrMissingFile = errors.New("there is no uploaded file associated with the given key")
  983. // SaveMultipartFile saves multipart file fh under the given filename path.
  984. func SaveMultipartFile(fh *multipart.FileHeader, path string) (err error) {
  985. var (
  986. f multipart.File
  987. ff *os.File
  988. )
  989. f, err = fh.Open()
  990. if err != nil {
  991. return err
  992. }
  993. var ok bool
  994. if ff, ok = f.(*os.File); ok {
  995. // Windows can't rename files that are opened.
  996. if err = f.Close(); err != nil {
  997. return err
  998. }
  999. // If renaming fails we try the normal copying method.
  1000. // Renaming could fail if the files are on different devices.
  1001. if os.Rename(ff.Name(), path) == nil {
  1002. return nil
  1003. }
  1004. // Reopen f for the code below.
  1005. if f, err = fh.Open(); err != nil {
  1006. return err
  1007. }
  1008. }
  1009. defer func() {
  1010. e := f.Close()
  1011. if err == nil {
  1012. err = e
  1013. }
  1014. }()
  1015. if ff, err = os.Create(path); err != nil {
  1016. return err
  1017. }
  1018. defer func() {
  1019. e := ff.Close()
  1020. if err == nil {
  1021. err = e
  1022. }
  1023. }()
  1024. _, err = copyZeroAlloc(ff, f)
  1025. return err
  1026. }
  1027. // FormValue returns form value associated with the given key.
  1028. //
  1029. // The value is searched in the following places:
  1030. //
  1031. // - Query string.
  1032. // - POST or PUT body.
  1033. //
  1034. // There are more fine-grained methods for obtaining form values:
  1035. //
  1036. // - QueryArgs for obtaining values from query string.
  1037. // - PostArgs for obtaining values from POST or PUT body.
  1038. // - MultipartForm for obtaining values from multipart form.
  1039. // - FormFile for obtaining uploaded files.
  1040. //
  1041. // The returned value is valid until your request handler returns.
  1042. func (ctx *RequestCtx) FormValue(key string) []byte {
  1043. if ctx.formValueFunc != nil {
  1044. return ctx.formValueFunc(ctx, key)
  1045. }
  1046. return defaultFormValue(ctx, key)
  1047. }
  1048. type FormValueFunc func(*RequestCtx, string) []byte
  1049. var (
  1050. defaultFormValue = func(ctx *RequestCtx, key string) []byte {
  1051. v := ctx.QueryArgs().Peek(key)
  1052. if len(v) > 0 {
  1053. return v
  1054. }
  1055. v = ctx.PostArgs().Peek(key)
  1056. if len(v) > 0 {
  1057. return v
  1058. }
  1059. mf, err := ctx.MultipartForm()
  1060. if err == nil && mf.Value != nil {
  1061. vv := mf.Value[key]
  1062. if len(vv) > 0 {
  1063. return []byte(vv[0])
  1064. }
  1065. }
  1066. return nil
  1067. }
  1068. // NetHttpFormValueFunc gives consistent behavior with net/http.
  1069. // POST and PUT body parameters take precedence over URL query string values.
  1070. //
  1071. //nolint:staticcheck // backwards compatibility
  1072. NetHttpFormValueFunc = func(ctx *RequestCtx, key string) []byte {
  1073. v := ctx.PostArgs().Peek(key)
  1074. if len(v) > 0 {
  1075. return v
  1076. }
  1077. mf, err := ctx.MultipartForm()
  1078. if err == nil && mf.Value != nil {
  1079. vv := mf.Value[key]
  1080. if len(vv) > 0 {
  1081. return []byte(vv[0])
  1082. }
  1083. }
  1084. v = ctx.QueryArgs().Peek(key)
  1085. if len(v) > 0 {
  1086. return v
  1087. }
  1088. return nil
  1089. }
  1090. )
  1091. // IsGet returns true if request method is GET.
  1092. func (ctx *RequestCtx) IsGet() bool {
  1093. return ctx.Request.Header.IsGet()
  1094. }
  1095. // IsPost returns true if request method is POST.
  1096. func (ctx *RequestCtx) IsPost() bool {
  1097. return ctx.Request.Header.IsPost()
  1098. }
  1099. // IsPut returns true if request method is PUT.
  1100. func (ctx *RequestCtx) IsPut() bool {
  1101. return ctx.Request.Header.IsPut()
  1102. }
  1103. // IsDelete returns true if request method is DELETE.
  1104. func (ctx *RequestCtx) IsDelete() bool {
  1105. return ctx.Request.Header.IsDelete()
  1106. }
  1107. // IsConnect returns true if request method is CONNECT.
  1108. func (ctx *RequestCtx) IsConnect() bool {
  1109. return ctx.Request.Header.IsConnect()
  1110. }
  1111. // IsOptions returns true if request method is OPTIONS.
  1112. func (ctx *RequestCtx) IsOptions() bool {
  1113. return ctx.Request.Header.IsOptions()
  1114. }
  1115. // IsTrace returns true if request method is TRACE.
  1116. func (ctx *RequestCtx) IsTrace() bool {
  1117. return ctx.Request.Header.IsTrace()
  1118. }
  1119. // IsPatch returns true if request method is PATCH.
  1120. func (ctx *RequestCtx) IsPatch() bool {
  1121. return ctx.Request.Header.IsPatch()
  1122. }
  1123. // Method return request method.
  1124. //
  1125. // Returned value is valid until your request handler returns.
  1126. func (ctx *RequestCtx) Method() []byte {
  1127. return ctx.Request.Header.Method()
  1128. }
  1129. // IsHead returns true if request method is HEAD.
  1130. func (ctx *RequestCtx) IsHead() bool {
  1131. return ctx.Request.Header.IsHead()
  1132. }
  1133. // RemoteAddr returns client address for the given request.
  1134. //
  1135. // Always returns non-nil result.
  1136. func (ctx *RequestCtx) RemoteAddr() net.Addr {
  1137. if ctx.remoteAddr != nil {
  1138. return ctx.remoteAddr
  1139. }
  1140. if ctx.c == nil {
  1141. return zeroTCPAddr
  1142. }
  1143. addr := ctx.c.RemoteAddr()
  1144. if addr == nil {
  1145. return zeroTCPAddr
  1146. }
  1147. return addr
  1148. }
  1149. // SetRemoteAddr sets remote address to the given value.
  1150. //
  1151. // Set nil value to restore default behaviour for using
  1152. // connection remote address.
  1153. func (ctx *RequestCtx) SetRemoteAddr(remoteAddr net.Addr) {
  1154. ctx.remoteAddr = remoteAddr
  1155. }
  1156. // LocalAddr returns server address for the given request.
  1157. //
  1158. // Always returns non-nil result.
  1159. func (ctx *RequestCtx) LocalAddr() net.Addr {
  1160. if ctx.c == nil {
  1161. return zeroTCPAddr
  1162. }
  1163. addr := ctx.c.LocalAddr()
  1164. if addr == nil {
  1165. return zeroTCPAddr
  1166. }
  1167. return addr
  1168. }
  1169. // RemoteIP returns the client ip the request came from.
  1170. //
  1171. // Always returns non-nil result.
  1172. func (ctx *RequestCtx) RemoteIP() net.IP {
  1173. return addrToIP(ctx.RemoteAddr())
  1174. }
  1175. // LocalIP returns the server ip the request came to.
  1176. //
  1177. // Always returns non-nil result.
  1178. func (ctx *RequestCtx) LocalIP() net.IP {
  1179. return addrToIP(ctx.LocalAddr())
  1180. }
  1181. func addrToIP(addr net.Addr) net.IP {
  1182. x, ok := addr.(*net.TCPAddr)
  1183. if !ok {
  1184. return net.IPv4zero
  1185. }
  1186. return x.IP
  1187. }
  1188. // Error sets response status code to the given value and sets response body
  1189. // to the given message.
  1190. //
  1191. // Warning: this will reset the response headers and body already set!
  1192. func (ctx *RequestCtx) Error(msg string, statusCode int) {
  1193. ctx.Response.Reset()
  1194. ctx.SetStatusCode(statusCode)
  1195. ctx.SetContentTypeBytes(defaultContentType)
  1196. ctx.SetBodyString(msg)
  1197. }
  1198. // Success sets response Content-Type and body to the given values.
  1199. func (ctx *RequestCtx) Success(contentType string, body []byte) {
  1200. ctx.SetContentType(contentType)
  1201. ctx.SetBody(body)
  1202. }
  1203. // SuccessString sets response Content-Type and body to the given values.
  1204. func (ctx *RequestCtx) SuccessString(contentType, body string) {
  1205. ctx.SetContentType(contentType)
  1206. ctx.SetBodyString(body)
  1207. }
  1208. // Redirect sets 'Location: uri' response header and sets the given statusCode.
  1209. //
  1210. // statusCode must have one of the following values:
  1211. //
  1212. // - StatusMovedPermanently (301)
  1213. // - StatusFound (302)
  1214. // - StatusSeeOther (303)
  1215. // - StatusTemporaryRedirect (307)
  1216. // - StatusPermanentRedirect (308)
  1217. //
  1218. // All other statusCode values are replaced by StatusFound (302).
  1219. //
  1220. // The redirect uri may be either absolute or relative to the current
  1221. // request uri. Fasthttp will always send an absolute uri back to the client.
  1222. // To send a relative uri you can use the following code:
  1223. //
  1224. // strLocation = []byte("Location") // Put this with your top level var () declarations.
  1225. // ctx.Response.Header.SetCanonical(strLocation, "/relative?uri")
  1226. // ctx.Response.SetStatusCode(fasthttp.StatusMovedPermanently)
  1227. func (ctx *RequestCtx) Redirect(uri string, statusCode int) {
  1228. u := AcquireURI()
  1229. ctx.URI().CopyTo(u)
  1230. u.Update(uri)
  1231. ctx.redirect(u.FullURI(), statusCode)
  1232. ReleaseURI(u)
  1233. }
  1234. // RedirectBytes sets 'Location: uri' response header and sets
  1235. // the given statusCode.
  1236. //
  1237. // statusCode must have one of the following values:
  1238. //
  1239. // - StatusMovedPermanently (301)
  1240. // - StatusFound (302)
  1241. // - StatusSeeOther (303)
  1242. // - StatusTemporaryRedirect (307)
  1243. // - StatusPermanentRedirect (308)
  1244. //
  1245. // All other statusCode values are replaced by StatusFound (302).
  1246. //
  1247. // The redirect uri may be either absolute or relative to the current
  1248. // request uri. Fasthttp will always send an absolute uri back to the client.
  1249. // To send a relative uri you can use the following code:
  1250. //
  1251. // strLocation = []byte("Location") // Put this with your top level var () declarations.
  1252. // ctx.Response.Header.SetCanonical(strLocation, "/relative?uri")
  1253. // ctx.Response.SetStatusCode(fasthttp.StatusMovedPermanently)
  1254. func (ctx *RequestCtx) RedirectBytes(uri []byte, statusCode int) {
  1255. s := b2s(uri)
  1256. ctx.Redirect(s, statusCode)
  1257. }
  1258. func (ctx *RequestCtx) redirect(uri []byte, statusCode int) {
  1259. ctx.Response.Header.setNonSpecial(strLocation, uri)
  1260. statusCode = getRedirectStatusCode(statusCode)
  1261. ctx.Response.SetStatusCode(statusCode)
  1262. }
  1263. func getRedirectStatusCode(statusCode int) int {
  1264. if statusCode == StatusMovedPermanently || statusCode == StatusFound ||
  1265. statusCode == StatusSeeOther || statusCode == StatusTemporaryRedirect ||
  1266. statusCode == StatusPermanentRedirect {
  1267. return statusCode
  1268. }
  1269. return StatusFound
  1270. }
  1271. // SetBody sets response body to the given value.
  1272. //
  1273. // It is safe re-using body argument after the function returns.
  1274. func (ctx *RequestCtx) SetBody(body []byte) {
  1275. ctx.Response.SetBody(body)
  1276. }
  1277. // SetBodyString sets response body to the given value.
  1278. func (ctx *RequestCtx) SetBodyString(body string) {
  1279. ctx.Response.SetBodyString(body)
  1280. }
  1281. // ResetBody resets response body contents.
  1282. func (ctx *RequestCtx) ResetBody() {
  1283. ctx.Response.ResetBody()
  1284. }
  1285. // SendFile sends local file contents from the given path as response body.
  1286. //
  1287. // This is a shortcut to ServeFile(ctx, path).
  1288. //
  1289. // SendFile logs all the errors via ctx.Logger.
  1290. //
  1291. // See also ServeFile, FSHandler and FS.
  1292. //
  1293. // WARNING: do not pass any user supplied paths to this function!
  1294. // WARNING: if path is based on user input users will be able to request
  1295. // any file on your filesystem! Use fasthttp.FS with a sane Root instead.
  1296. func (ctx *RequestCtx) SendFile(path string) {
  1297. ServeFile(ctx, path)
  1298. }
  1299. // SendFileBytes sends local file contents from the given path as response body.
  1300. //
  1301. // This is a shortcut to ServeFileBytes(ctx, path).
  1302. //
  1303. // SendFileBytes logs all the errors via ctx.Logger.
  1304. //
  1305. // See also ServeFileBytes, FSHandler and FS.
  1306. //
  1307. // WARNING: do not pass any user supplied paths to this function!
  1308. // WARNING: if path is based on user input users will be able to request
  1309. // any file on your filesystem! Use fasthttp.FS with a sane Root instead.
  1310. func (ctx *RequestCtx) SendFileBytes(path []byte) {
  1311. ServeFileBytes(ctx, path)
  1312. }
  1313. // IfModifiedSince returns true if lastModified exceeds 'If-Modified-Since'
  1314. // value from the request header.
  1315. //
  1316. // The function returns true also 'If-Modified-Since' request header is missing.
  1317. func (ctx *RequestCtx) IfModifiedSince(lastModified time.Time) bool {
  1318. ifModStr := ctx.Request.Header.peek(strIfModifiedSince)
  1319. if len(ifModStr) == 0 {
  1320. return true
  1321. }
  1322. ifMod, err := ParseHTTPDate(ifModStr)
  1323. if err != nil {
  1324. return true
  1325. }
  1326. lastModified = lastModified.Truncate(time.Second)
  1327. return ifMod.Before(lastModified)
  1328. }
  1329. // NotModified resets response and sets '304 Not Modified' response status code.
  1330. func (ctx *RequestCtx) NotModified() {
  1331. ctx.Response.Reset()
  1332. ctx.SetStatusCode(StatusNotModified)
  1333. }
  1334. // NotFound resets response and sets '404 Not Found' response status code.
  1335. func (ctx *RequestCtx) NotFound() {
  1336. ctx.Response.Reset()
  1337. ctx.SetStatusCode(StatusNotFound)
  1338. ctx.SetBodyString("404 Page not found")
  1339. }
  1340. // Write writes p into response body.
  1341. func (ctx *RequestCtx) Write(p []byte) (int, error) {
  1342. ctx.Response.AppendBody(p)
  1343. return len(p), nil
  1344. }
  1345. // WriteString appends s to response body.
  1346. func (ctx *RequestCtx) WriteString(s string) (int, error) {
  1347. ctx.Response.AppendBodyString(s)
  1348. return len(s), nil
  1349. }
  1350. // PostBody returns POST request body.
  1351. //
  1352. // The returned bytes are valid until your request handler returns.
  1353. func (ctx *RequestCtx) PostBody() []byte {
  1354. return ctx.Request.Body()
  1355. }
  1356. // SetBodyStream sets response body stream and, optionally body size.
  1357. //
  1358. // bodyStream.Close() is called after finishing reading all body data
  1359. // if it implements io.Closer.
  1360. //
  1361. // If bodySize is >= 0, then bodySize bytes must be provided by bodyStream
  1362. // before returning io.EOF.
  1363. //
  1364. // If bodySize < 0, then bodyStream is read until io.EOF.
  1365. //
  1366. // See also SetBodyStreamWriter.
  1367. func (ctx *RequestCtx) SetBodyStream(bodyStream io.Reader, bodySize int) {
  1368. ctx.Response.SetBodyStream(bodyStream, bodySize)
  1369. }
  1370. // SetBodyStreamWriter registers the given stream writer for populating
  1371. // response body.
  1372. //
  1373. // Access to RequestCtx and/or its members is forbidden from sw.
  1374. //
  1375. // This function may be used in the following cases:
  1376. //
  1377. // - if response body is too big (more than 10MB).
  1378. // - if response body is streamed from slow external sources.
  1379. // - if response body must be streamed to the client in chunks.
  1380. // (aka `http server push`).
  1381. func (ctx *RequestCtx) SetBodyStreamWriter(sw StreamWriter) {
  1382. ctx.Response.SetBodyStreamWriter(sw)
  1383. }
  1384. // IsBodyStream returns true if response body is set via SetBodyStream*.
  1385. func (ctx *RequestCtx) IsBodyStream() bool {
  1386. return ctx.Response.IsBodyStream()
  1387. }
  1388. // Logger returns logger, which may be used for logging arbitrary
  1389. // request-specific messages inside RequestHandler.
  1390. //
  1391. // Each message logged via returned logger contains request-specific information
  1392. // such as request id, request duration, local address, remote address,
  1393. // request method and request url.
  1394. //
  1395. // It is safe re-using returned logger for logging multiple messages
  1396. // for the current request.
  1397. //
  1398. // The returned logger is valid until your request handler returns.
  1399. func (ctx *RequestCtx) Logger() Logger {
  1400. if ctx.logger.ctx == nil {
  1401. ctx.logger.ctx = ctx
  1402. }
  1403. if ctx.logger.logger == nil {
  1404. ctx.logger.logger = ctx.s.logger()
  1405. }
  1406. return &ctx.logger
  1407. }
  1408. // TimeoutError sets response status code to StatusRequestTimeout and sets
  1409. // body to the given msg.
  1410. //
  1411. // All response modifications after TimeoutError call are ignored.
  1412. //
  1413. // TimeoutError MUST be called before returning from RequestHandler if there are
  1414. // references to ctx and/or its members in other goroutines remain.
  1415. //
  1416. // Usage of this function is discouraged. Prefer eliminating ctx references
  1417. // from pending goroutines instead of using this function.
  1418. func (ctx *RequestCtx) TimeoutError(msg string) {
  1419. ctx.TimeoutErrorWithCode(msg, StatusRequestTimeout)
  1420. }
  1421. // TimeoutErrorWithCode sets response body to msg and response status
  1422. // code to statusCode.
  1423. //
  1424. // All response modifications after TimeoutErrorWithCode call are ignored.
  1425. //
  1426. // TimeoutErrorWithCode MUST be called before returning from RequestHandler
  1427. // if there are references to ctx and/or its members in other goroutines remain.
  1428. //
  1429. // Usage of this function is discouraged. Prefer eliminating ctx references
  1430. // from pending goroutines instead of using this function.
  1431. func (ctx *RequestCtx) TimeoutErrorWithCode(msg string, statusCode int) {
  1432. var resp Response
  1433. resp.SetStatusCode(statusCode)
  1434. resp.SetBodyString(msg)
  1435. ctx.TimeoutErrorWithResponse(&resp)
  1436. }
  1437. // TimeoutErrorWithResponse marks the ctx as timed out and sends the given
  1438. // response to the client.
  1439. //
  1440. // All ctx modifications after TimeoutErrorWithResponse call are ignored.
  1441. //
  1442. // TimeoutErrorWithResponse MUST be called before returning from RequestHandler
  1443. // if there are references to ctx and/or its members in other goroutines remain.
  1444. //
  1445. // Usage of this function is discouraged. Prefer eliminating ctx references
  1446. // from pending goroutines instead of using this function.
  1447. func (ctx *RequestCtx) TimeoutErrorWithResponse(resp *Response) {
  1448. respCopy := &Response{}
  1449. resp.CopyTo(respCopy)
  1450. ctx.timeoutResponse = respCopy
  1451. }
  1452. // NextProto adds nph to be processed when key is negotiated when TLS
  1453. // connection is established.
  1454. //
  1455. // This function can only be called before the server is started.
  1456. func (s *Server) NextProto(key string, nph ServeHandler) {
  1457. if s.nextProtos == nil {
  1458. s.nextProtos = make(map[string]ServeHandler)
  1459. }
  1460. s.configTLS()
  1461. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, key)
  1462. s.nextProtos[key] = nph
  1463. }
  1464. func (s *Server) getNextProto(c net.Conn) (string, error) {
  1465. if tlsConn, ok := c.(connTLSer); ok {
  1466. if s.ReadTimeout > 0 {
  1467. if err := c.SetReadDeadline(time.Now().Add(s.ReadTimeout)); err != nil {
  1468. return "", err
  1469. }
  1470. }
  1471. if s.WriteTimeout > 0 {
  1472. if err := c.SetWriteDeadline(time.Now().Add(s.WriteTimeout)); err != nil {
  1473. return "", err
  1474. }
  1475. }
  1476. err := tlsConn.Handshake()
  1477. if err == nil {
  1478. return tlsConn.ConnectionState().NegotiatedProtocol, nil
  1479. }
  1480. }
  1481. return "", nil
  1482. }
  1483. // ListenAndServe serves HTTP requests from the given TCP4 addr.
  1484. //
  1485. // Pass custom listener to Serve if you need listening on non-TCP4 media
  1486. // such as IPv6.
  1487. //
  1488. // Accepted connections are configured to enable TCP keep-alives.
  1489. func (s *Server) ListenAndServe(addr string) error {
  1490. ln, err := net.Listen("tcp4", addr)
  1491. if err != nil {
  1492. return err
  1493. }
  1494. return s.Serve(ln)
  1495. }
  1496. // ListenAndServeUNIX serves HTTP requests from the given UNIX addr.
  1497. //
  1498. // The function deletes existing file at addr before starting serving.
  1499. //
  1500. // The server sets the given file mode for the UNIX addr.
  1501. func (s *Server) ListenAndServeUNIX(addr string, mode os.FileMode) error {
  1502. if err := os.Remove(addr); err != nil && !os.IsNotExist(err) {
  1503. return fmt.Errorf("unexpected error when trying to remove unix socket file %q: %w", addr, err)
  1504. }
  1505. ln, err := net.Listen("unix", addr)
  1506. if err != nil {
  1507. return err
  1508. }
  1509. if err = os.Chmod(addr, mode); err != nil {
  1510. return fmt.Errorf("cannot chmod %#o for %q: %w", mode, addr, err)
  1511. }
  1512. return s.Serve(ln)
  1513. }
  1514. // ListenAndServeTLS serves HTTPS requests from the given TCP4 addr.
  1515. //
  1516. // certFile and keyFile are paths to TLS certificate and key files.
  1517. //
  1518. // Pass custom listener to Serve if you need listening on non-TCP4 media
  1519. // such as IPv6.
  1520. //
  1521. // If the certFile or keyFile has not been provided to the server structure,
  1522. // the function will use the previously added TLS configuration.
  1523. //
  1524. // Accepted connections are configured to enable TCP keep-alives.
  1525. func (s *Server) ListenAndServeTLS(addr, certFile, keyFile string) error {
  1526. ln, err := net.Listen("tcp4", addr)
  1527. if err != nil {
  1528. return err
  1529. }
  1530. return s.ServeTLS(ln, certFile, keyFile)
  1531. }
  1532. // ListenAndServeTLSEmbed serves HTTPS requests from the given TCP4 addr.
  1533. //
  1534. // certData and keyData must contain valid TLS certificate and key data.
  1535. //
  1536. // Pass custom listener to Serve if you need listening on arbitrary media
  1537. // such as IPv6.
  1538. //
  1539. // If the certFile or keyFile has not been provided the server structure,
  1540. // the function will use previously added TLS configuration.
  1541. //
  1542. // Accepted connections are configured to enable TCP keep-alives.
  1543. func (s *Server) ListenAndServeTLSEmbed(addr string, certData, keyData []byte) error {
  1544. ln, err := net.Listen("tcp4", addr)
  1545. if err != nil {
  1546. return err
  1547. }
  1548. return s.ServeTLSEmbed(ln, certData, keyData)
  1549. }
  1550. // ServeTLS serves HTTPS requests from the given listener.
  1551. //
  1552. // certFile and keyFile are paths to TLS certificate and key files.
  1553. //
  1554. // If the certFile or keyFile has not been provided the server structure,
  1555. // the function will use previously added TLS configuration.
  1556. func (s *Server) ServeTLS(ln net.Listener, certFile, keyFile string) error {
  1557. s.mu.Lock()
  1558. s.configTLS()
  1559. configHasCert := len(s.TLSConfig.Certificates) > 0 || s.TLSConfig.GetCertificate != nil
  1560. if !configHasCert || certFile != "" || keyFile != "" {
  1561. if err := s.AppendCert(certFile, keyFile); err != nil {
  1562. s.mu.Unlock()
  1563. return err
  1564. }
  1565. }
  1566. s.mu.Unlock()
  1567. return s.Serve(
  1568. tls.NewListener(ln, s.TLSConfig.Clone()),
  1569. )
  1570. }
  1571. // ServeTLSEmbed serves HTTPS requests from the given listener.
  1572. //
  1573. // certData and keyData must contain valid TLS certificate and key data.
  1574. //
  1575. // If the certFile or keyFile has not been provided the server structure,
  1576. // the function will use previously added TLS configuration.
  1577. func (s *Server) ServeTLSEmbed(ln net.Listener, certData, keyData []byte) error {
  1578. s.mu.Lock()
  1579. s.configTLS()
  1580. configHasCert := len(s.TLSConfig.Certificates) > 0 || s.TLSConfig.GetCertificate != nil
  1581. if !configHasCert || len(certData) != 0 || len(keyData) != 0 {
  1582. if err := s.AppendCertEmbed(certData, keyData); err != nil {
  1583. s.mu.Unlock()
  1584. return err
  1585. }
  1586. }
  1587. s.mu.Unlock()
  1588. return s.Serve(
  1589. tls.NewListener(ln, s.TLSConfig.Clone()),
  1590. )
  1591. }
  1592. // AppendCert appends certificate and keyfile to TLS Configuration.
  1593. //
  1594. // This function allows programmer to handle multiple domains
  1595. // in one server structure. See examples/multidomain.
  1596. func (s *Server) AppendCert(certFile, keyFile string) error {
  1597. if certFile == "" && keyFile == "" {
  1598. return errNoCertOrKeyProvided
  1599. }
  1600. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  1601. if err != nil {
  1602. return fmt.Errorf("cannot load TLS key pair from certFile=%q and keyFile=%q: %w", certFile, keyFile, err)
  1603. }
  1604. s.configTLS()
  1605. s.TLSConfig.Certificates = append(s.TLSConfig.Certificates, cert)
  1606. return nil
  1607. }
  1608. // AppendCertEmbed does the same as AppendCert but using in-memory data.
  1609. func (s *Server) AppendCertEmbed(certData, keyData []byte) error {
  1610. if len(certData) == 0 && len(keyData) == 0 {
  1611. return errNoCertOrKeyProvided
  1612. }
  1613. cert, err := tls.X509KeyPair(certData, keyData)
  1614. if err != nil {
  1615. return fmt.Errorf("cannot load TLS key pair from the provided certData(%d) and keyData(%d): %w",
  1616. len(certData), len(keyData), err)
  1617. }
  1618. s.configTLS()
  1619. s.TLSConfig.Certificates = append(s.TLSConfig.Certificates, cert)
  1620. return nil
  1621. }
  1622. func (s *Server) configTLS() {
  1623. if s.TLSConfig == nil {
  1624. s.TLSConfig = &tls.Config{}
  1625. }
  1626. }
  1627. // DefaultConcurrency is the maximum number of concurrent connections
  1628. // the Server may serve by default (i.e. if Server.Concurrency isn't set).
  1629. const DefaultConcurrency = 256 * 1024
  1630. // Serve serves incoming connections from the given listener.
  1631. //
  1632. // Serve blocks until the given listener returns permanent error.
  1633. func (s *Server) Serve(ln net.Listener) error {
  1634. var lastOverflowErrorTime time.Time
  1635. var lastPerIPErrorTime time.Time
  1636. maxWorkersCount := s.getConcurrency()
  1637. s.mu.Lock()
  1638. s.ln = append(s.ln, ln)
  1639. if s.done == nil {
  1640. s.done = make(chan struct{})
  1641. }
  1642. if s.concurrencyCh == nil {
  1643. s.concurrencyCh = make(chan struct{}, maxWorkersCount)
  1644. }
  1645. s.mu.Unlock()
  1646. wp := &workerPool{
  1647. WorkerFunc: s.serveConn,
  1648. MaxWorkersCount: maxWorkersCount,
  1649. LogAllErrors: s.LogAllErrors,
  1650. MaxIdleWorkerDuration: s.MaxIdleWorkerDuration,
  1651. Logger: s.logger(),
  1652. connState: s.setState,
  1653. }
  1654. wp.Start()
  1655. // Count our waiting to accept a connection as an open connection.
  1656. // This way we can't get into any weird state where just after accepting
  1657. // a connection Shutdown is called which reads open as 0 because it isn't
  1658. // incremented yet.
  1659. s.open.Add(1)
  1660. defer s.open.Add(-1)
  1661. for {
  1662. c, err := acceptConn(s, ln, &lastPerIPErrorTime)
  1663. if err != nil {
  1664. wp.Stop()
  1665. if err == io.EOF {
  1666. return nil
  1667. }
  1668. return err
  1669. }
  1670. s.setState(c, StateNew)
  1671. s.open.Add(1)
  1672. if !wp.Serve(c) {
  1673. s.open.Add(-1)
  1674. s.rejectedRequestsCount.Add(1)
  1675. s.writeFastError(c, StatusServiceUnavailable,
  1676. "The connection cannot be served because Server.Concurrency limit exceeded")
  1677. c.Close()
  1678. s.setState(c, StateClosed)
  1679. if time.Since(lastOverflowErrorTime) > time.Minute {
  1680. s.logger().Printf("The incoming connection cannot be served, because %d concurrent connections are served. "+
  1681. "Try increasing Server.Concurrency", maxWorkersCount)
  1682. lastOverflowErrorTime = time.Now()
  1683. }
  1684. // The current server reached concurrency limit,
  1685. // so give other concurrently running servers a chance
  1686. // accepting incoming connections on the same address.
  1687. //
  1688. // There is a hope other servers didn't reach their
  1689. // concurrency limits yet :)
  1690. //
  1691. // See also: https://github.com/valyala/fasthttp/pull/485#discussion_r239994990
  1692. if s.SleepWhenConcurrencyLimitsExceeded > 0 {
  1693. time.Sleep(s.SleepWhenConcurrencyLimitsExceeded)
  1694. }
  1695. }
  1696. }
  1697. }
  1698. // Shutdown gracefully shuts down the server without interrupting any active connections.
  1699. // Shutdown works by first closing all open listeners and then waiting indefinitely for all connections
  1700. // to return to idle and then shut down.
  1701. //
  1702. // When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return nil.
  1703. // Make sure the program doesn't exit and waits instead for Shutdown to return.
  1704. //
  1705. // Shutdown does not close keepalive connections so it's recommended to set ReadTimeout and IdleTimeout to something else than 0.
  1706. func (s *Server) Shutdown() error {
  1707. return s.ShutdownWithContext(context.Background())
  1708. }
  1709. // ShutdownWithContext gracefully shuts down the server without interrupting any active connections.
  1710. // ShutdownWithContext works by first closing all open listeners and then waiting for all connections to return to idle
  1711. // or context timeout and then shut down.
  1712. //
  1713. // When ShutdownWithContext is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return nil.
  1714. // Make sure the program doesn't exit and waits instead for Shutdown to return.
  1715. //
  1716. // ShutdownWithContext does not close keepalive connections so it's recommended to set ReadTimeout and IdleTimeout
  1717. // to something else than 0.
  1718. //
  1719. // When ShutdownWithContext returns errors, any operation to the Server is unavailable.
  1720. func (s *Server) ShutdownWithContext(ctx context.Context) (err error) {
  1721. s.mu.Lock()
  1722. defer s.mu.Unlock()
  1723. s.stop.Store(1)
  1724. defer s.stop.Store(0)
  1725. if s.ln == nil {
  1726. return nil
  1727. }
  1728. lnerr := s.closeListenersLocked()
  1729. if s.done != nil {
  1730. close(s.done)
  1731. }
  1732. // Closing the listener will make Serve() call Stop on the worker pool.
  1733. // Setting .stop to 1 will make serveConn() break out of its loop.
  1734. // Now we just have to wait until all workers are done or timeout.
  1735. ticker := time.NewTicker(time.Millisecond * 100)
  1736. defer ticker.Stop()
  1737. for {
  1738. s.closeIdleConns()
  1739. if open := s.open.Load(); open == 0 {
  1740. // There may be a pending request to call ctx.Done(). Therefore, we only set it to nil when open == 0.
  1741. s.done = nil
  1742. return lnerr
  1743. }
  1744. // This is not an optimal solution but using a sync.WaitGroup
  1745. // here causes data races as it's hard to prevent Add() to be called
  1746. // while Wait() is waiting.
  1747. select {
  1748. case <-ctx.Done():
  1749. return ctx.Err()
  1750. case <-ticker.C:
  1751. continue
  1752. }
  1753. }
  1754. }
  1755. type connKeepAliveer interface {
  1756. SetKeepAlive(keepalive bool) error
  1757. SetKeepAlivePeriod(d time.Duration) error
  1758. io.Closer
  1759. }
  1760. func acceptConn(s *Server, ln net.Listener, lastPerIPErrorTime *time.Time) (net.Conn, error) {
  1761. for {
  1762. c, err := ln.Accept()
  1763. if err != nil {
  1764. if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
  1765. s.logger().Printf("Timeout error when accepting new connections: %v", netErr)
  1766. time.Sleep(time.Second)
  1767. continue
  1768. }
  1769. if err != io.EOF && !strings.Contains(err.Error(), "use of closed network connection") {
  1770. s.logger().Printf("Permanent error when accepting new connections: %v", err)
  1771. return nil, err
  1772. }
  1773. return nil, io.EOF
  1774. }
  1775. if tc, ok := c.(connKeepAliveer); ok && s.TCPKeepalive {
  1776. if err := tc.SetKeepAlive(s.TCPKeepalive); err != nil {
  1777. _ = tc.Close()
  1778. return nil, err
  1779. }
  1780. if s.TCPKeepalivePeriod > 0 {
  1781. if err := tc.SetKeepAlivePeriod(s.TCPKeepalivePeriod); err != nil {
  1782. _ = tc.Close()
  1783. return nil, err
  1784. }
  1785. }
  1786. }
  1787. if s.MaxConnsPerIP > 0 {
  1788. pic := wrapPerIPConn(s, c)
  1789. if pic == nil {
  1790. if time.Since(*lastPerIPErrorTime) > time.Minute {
  1791. s.logger().Printf("The number of connections from %s exceeds MaxConnsPerIP=%d",
  1792. getConnIP4(c), s.MaxConnsPerIP)
  1793. *lastPerIPErrorTime = time.Now()
  1794. }
  1795. continue
  1796. }
  1797. c = pic
  1798. }
  1799. return c, nil
  1800. }
  1801. }
  1802. func wrapPerIPConn(s *Server, c net.Conn) net.Conn {
  1803. ip := getUint32IP(c)
  1804. if ip == 0 {
  1805. return c
  1806. }
  1807. n := s.perIPConnCounter.Register(ip)
  1808. if n > s.MaxConnsPerIP {
  1809. s.perIPConnCounter.Unregister(ip)
  1810. s.writeFastError(c, StatusTooManyRequests, "The number of connections from your ip exceeds MaxConnsPerIP")
  1811. c.Close()
  1812. return nil
  1813. }
  1814. return acquirePerIPConn(c, ip, &s.perIPConnCounter)
  1815. }
  1816. var defaultLogger = Logger(log.New(os.Stderr, "", log.LstdFlags))
  1817. func (s *Server) logger() Logger {
  1818. if s.Logger != nil {
  1819. return s.Logger
  1820. }
  1821. return defaultLogger
  1822. }
  1823. var (
  1824. // ErrPerIPConnLimit may be returned from ServeConn if the number of connections
  1825. // per ip exceeds Server.MaxConnsPerIP.
  1826. ErrPerIPConnLimit = errors.New("too many connections per ip")
  1827. // ErrConcurrencyLimit may be returned from ServeConn if the number
  1828. // of concurrently served connections exceeds Server.Concurrency.
  1829. ErrConcurrencyLimit = errors.New("cannot serve the connection because Server.Concurrency concurrent connections are served")
  1830. )
  1831. // ServeConn serves HTTP requests from the given connection.
  1832. //
  1833. // ServeConn returns nil if all requests from the c are successfully served.
  1834. // It returns non-nil error otherwise.
  1835. //
  1836. // Connection c must immediately propagate all the data passed to Write()
  1837. // to the client. Otherwise requests' processing may hang.
  1838. //
  1839. // ServeConn closes c before returning.
  1840. func (s *Server) ServeConn(c net.Conn) error {
  1841. if s.MaxConnsPerIP > 0 {
  1842. pic := wrapPerIPConn(s, c)
  1843. if pic == nil {
  1844. return ErrPerIPConnLimit
  1845. }
  1846. c = pic
  1847. }
  1848. n := int(s.concurrency.Add(1)) // #nosec G115
  1849. if n > s.getConcurrency() {
  1850. s.concurrency.Add(^uint32(0))
  1851. s.writeFastError(c, StatusServiceUnavailable, "The connection cannot be served because Server.Concurrency limit exceeded")
  1852. c.Close()
  1853. return ErrConcurrencyLimit
  1854. }
  1855. s.open.Add(1)
  1856. err := s.serveConn(c)
  1857. s.concurrency.Add(^uint32(0))
  1858. if err != errHijacked {
  1859. errc := c.Close()
  1860. s.setState(c, StateClosed)
  1861. if err == nil {
  1862. err = errc
  1863. }
  1864. } else {
  1865. err = nil
  1866. s.setState(c, StateHijacked)
  1867. }
  1868. return err
  1869. }
  1870. var errHijacked = errors.New("connection has been hijacked")
  1871. // GetCurrentConcurrency returns a number of currently served
  1872. // connections.
  1873. //
  1874. // This function is intended be used by monitoring systems.
  1875. func (s *Server) GetCurrentConcurrency() uint32 {
  1876. return s.concurrency.Load()
  1877. }
  1878. // GetOpenConnectionsCount returns a number of opened connections.
  1879. //
  1880. // This function is intended be used by monitoring systems.
  1881. func (s *Server) GetOpenConnectionsCount() int32 {
  1882. if s.stop.Load() == 0 {
  1883. // Decrement by one to avoid reporting the extra open value that gets
  1884. // counted while the server is listening.
  1885. return s.open.Load() - 1
  1886. }
  1887. // This is not perfect, because s.stop could have changed to zero
  1888. // before we load the value of s.open. However, in the common case
  1889. // this avoids underreporting open connections by 1 during server shutdown.
  1890. return s.open.Load()
  1891. }
  1892. // GetRejectedConnectionsCount returns a number of rejected connections.
  1893. //
  1894. // This function is intended be used by monitoring systems.
  1895. func (s *Server) GetRejectedConnectionsCount() uint32 {
  1896. return s.rejectedRequestsCount.Load()
  1897. }
  1898. func (s *Server) getConcurrency() int {
  1899. n := s.Concurrency
  1900. if n <= 0 {
  1901. n = DefaultConcurrency
  1902. }
  1903. return n
  1904. }
  1905. var globalConnID uint64
  1906. func nextConnID() uint64 {
  1907. return atomic.AddUint64(&globalConnID, 1)
  1908. }
  1909. // DefaultMaxRequestBodySize is the maximum request body size the server
  1910. // reads by default.
  1911. //
  1912. // See Server.MaxRequestBodySize for details.
  1913. const DefaultMaxRequestBodySize = 4 * 1024 * 1024
  1914. func (s *Server) idleTimeout() time.Duration {
  1915. if s.IdleTimeout != 0 {
  1916. return s.IdleTimeout
  1917. }
  1918. return s.ReadTimeout
  1919. }
  1920. func (s *Server) serveConnCleanup() {
  1921. s.open.Add(-1)
  1922. s.concurrency.Add(^uint32(0))
  1923. }
  1924. func (s *Server) serveConn(c net.Conn) error {
  1925. defer s.serveConnCleanup()
  1926. s.concurrency.Add(1)
  1927. proto, err := s.getNextProto(c)
  1928. if err != nil {
  1929. return err
  1930. }
  1931. if handler, ok := s.nextProtos[proto]; ok {
  1932. // Remove read or write deadlines that might have previously been set.
  1933. // The next handler is responsible for setting its own deadlines.
  1934. if s.ReadTimeout > 0 || s.WriteTimeout > 0 {
  1935. if err := c.SetDeadline(zeroTime); err != nil {
  1936. return err
  1937. }
  1938. }
  1939. return handler(c)
  1940. }
  1941. s.idleConnsMu.Lock()
  1942. if s.idleConns == nil {
  1943. s.idleConns = make(map[net.Conn]*atomic.Int64)
  1944. }
  1945. idleConnTime, ok := s.idleConns[c]
  1946. if !ok {
  1947. v := idleConnTimePool.Get()
  1948. if v == nil {
  1949. v = &atomic.Int64{}
  1950. }
  1951. idleConnTime = v.(*atomic.Int64)
  1952. s.idleConns[c] = idleConnTime
  1953. }
  1954. // Count the connection as Idle after 5 seconds.
  1955. // Same as net/http.Server:
  1956. // https://github.com/golang/go/blob/85d7bab91d9a3ed1f76842e4328973ea75efef54/src/net/http/server.go#L2834-L2836
  1957. idleConnTime.Store(time.Now().Add(time.Second * 5).Unix())
  1958. s.idleConnsMu.Unlock()
  1959. serverName := s.getServerName()
  1960. connRequestNum := uint64(0)
  1961. connID := nextConnID()
  1962. connTime := time.Now()
  1963. maxRequestBodySize := s.MaxRequestBodySize
  1964. if maxRequestBodySize <= 0 {
  1965. maxRequestBodySize = DefaultMaxRequestBodySize
  1966. }
  1967. writeTimeout := s.WriteTimeout
  1968. previousWriteTimeout := time.Duration(0)
  1969. ctx := s.acquireCtx(c)
  1970. ctx.connTime = connTime
  1971. isTLS := ctx.IsTLS()
  1972. var (
  1973. br *bufio.Reader
  1974. bw *bufio.Writer
  1975. timeoutResponse *Response
  1976. hijackHandler HijackHandler
  1977. hijackNoResponse bool
  1978. connectionClose bool
  1979. continueReadingRequest = true
  1980. )
  1981. for {
  1982. connRequestNum++
  1983. // If this is a keep-alive connection set the idle timeout.
  1984. if connRequestNum > 1 {
  1985. if d := s.idleTimeout(); d > 0 {
  1986. if err = c.SetReadDeadline(time.Now().Add(d)); err != nil {
  1987. break
  1988. }
  1989. }
  1990. }
  1991. if !s.ReduceMemoryUsage || br != nil {
  1992. if br == nil {
  1993. br = acquireReader(ctx)
  1994. }
  1995. // If this is a keep-alive connection we want to try and read the first bytes
  1996. // within the idle time.
  1997. if connRequestNum > 1 {
  1998. var b []byte
  1999. b, err = br.Peek(1)
  2000. if len(b) == 0 {
  2001. // If reading from a keep-alive connection returns nothing it means
  2002. // the connection was closed (either timeout or from the other side).
  2003. if err != io.EOF {
  2004. err = ErrNothingRead{error: err}
  2005. }
  2006. }
  2007. }
  2008. } else {
  2009. // If this is a keep-alive connection acquireByteReader will try to peek
  2010. // a couple of bytes already so the idle timeout will already be used.
  2011. br, err = acquireByteReader(&ctx)
  2012. }
  2013. ctx.Request.isTLS = isTLS
  2014. ctx.Response.Header.noDefaultContentType = s.NoDefaultContentType
  2015. ctx.Response.Header.noDefaultDate = s.NoDefaultDate
  2016. // Secure header error logs configuration
  2017. ctx.Request.Header.secureErrorLogMessage = s.SecureErrorLogMessage
  2018. ctx.Response.Header.secureErrorLogMessage = s.SecureErrorLogMessage
  2019. ctx.Request.secureErrorLogMessage = s.SecureErrorLogMessage
  2020. ctx.Response.secureErrorLogMessage = s.SecureErrorLogMessage
  2021. if err == nil {
  2022. s.setState(c, StateActive)
  2023. idleConnTime.Store(0)
  2024. if s.ReadTimeout > 0 {
  2025. if err = c.SetReadDeadline(time.Now().Add(s.ReadTimeout)); err != nil {
  2026. break
  2027. }
  2028. } else if s.IdleTimeout > 0 && connRequestNum > 1 {
  2029. // If this was an idle connection and the server has an IdleTimeout but
  2030. // no ReadTimeout then we should remove the ReadTimeout.
  2031. if err = c.SetReadDeadline(zeroTime); err != nil {
  2032. break
  2033. }
  2034. }
  2035. if s.DisableHeaderNamesNormalizing {
  2036. ctx.Request.Header.DisableNormalizing()
  2037. ctx.Response.Header.DisableNormalizing()
  2038. }
  2039. // Reading Headers.
  2040. //
  2041. // If we have pipeline response in the outgoing buffer,
  2042. // we only want to try and read the next headers once.
  2043. // If we have to wait for the next request we flush the
  2044. // outgoing buffer first so it doesn't have to wait.
  2045. if bw != nil && bw.Buffered() > 0 {
  2046. err = ctx.Request.Header.readLoop(br, false)
  2047. if err == ErrNeedMore {
  2048. err = bw.Flush()
  2049. if err != nil {
  2050. break
  2051. }
  2052. err = ctx.Request.Header.Read(br)
  2053. }
  2054. } else {
  2055. err = ctx.Request.Header.Read(br)
  2056. }
  2057. if err == nil {
  2058. if onHdrRecv := s.HeaderReceived; onHdrRecv != nil {
  2059. reqConf := onHdrRecv(&ctx.Request.Header)
  2060. if reqConf.ReadTimeout > 0 {
  2061. deadline := time.Now().Add(reqConf.ReadTimeout)
  2062. if err = c.SetReadDeadline(deadline); err != nil {
  2063. break
  2064. }
  2065. }
  2066. switch {
  2067. case reqConf.MaxRequestBodySize > 0:
  2068. maxRequestBodySize = reqConf.MaxRequestBodySize
  2069. case s.MaxRequestBodySize > 0:
  2070. maxRequestBodySize = s.MaxRequestBodySize
  2071. default:
  2072. maxRequestBodySize = DefaultMaxRequestBodySize
  2073. }
  2074. if reqConf.WriteTimeout > 0 {
  2075. writeTimeout = reqConf.WriteTimeout
  2076. } else {
  2077. writeTimeout = s.WriteTimeout
  2078. }
  2079. }
  2080. if err == nil {
  2081. if err = ctx.Request.parseURI(); err != nil {
  2082. bw = s.writeErrorResponse(bw, ctx, serverName, err)
  2083. break
  2084. }
  2085. }
  2086. if err == nil {
  2087. // read body
  2088. if s.StreamRequestBody {
  2089. err = ctx.Request.readBodyStream(br, maxRequestBodySize, s.GetOnly, !s.DisablePreParseMultipartForm)
  2090. } else {
  2091. err = ctx.Request.readLimitBody(br, maxRequestBodySize, s.GetOnly, !s.DisablePreParseMultipartForm)
  2092. }
  2093. }
  2094. }
  2095. // When StreamRequestBody is set to true, we cannot safely release br.
  2096. // For example, when using chunked encoding, it's possible that br has only read the request headers.
  2097. if (!s.StreamRequestBody && s.ReduceMemoryUsage && br.Buffered() == 0) || err != nil {
  2098. releaseReader(s, br)
  2099. br = nil
  2100. }
  2101. }
  2102. if err != nil {
  2103. if err == io.EOF {
  2104. err = nil
  2105. } else if nr, ok := err.(ErrNothingRead); ok {
  2106. if connRequestNum > 1 {
  2107. // This is not the first request and we haven't read a single byte
  2108. // of a new request yet. This means it's just a keep-alive connection
  2109. // closing down either because the remote closed it or because
  2110. // or a read timeout on our side. Either way just close the connection
  2111. // and don't return any error response.
  2112. err = nil
  2113. } else {
  2114. err = nr.error
  2115. }
  2116. }
  2117. if err != nil {
  2118. bw = s.writeErrorResponse(bw, ctx, serverName, err)
  2119. }
  2120. break
  2121. }
  2122. // 'Expect: 100-continue' request handling.
  2123. // See https://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3 for details.
  2124. if ctx.Request.MayContinue() {
  2125. // Allow the ability to deny reading the incoming request body
  2126. if s.ContinueHandler != nil {
  2127. if continueReadingRequest = s.ContinueHandler(&ctx.Request.Header); !continueReadingRequest {
  2128. if br != nil {
  2129. br.Reset(ctx.c)
  2130. }
  2131. ctx.SetStatusCode(StatusExpectationFailed)
  2132. }
  2133. }
  2134. if continueReadingRequest {
  2135. if bw == nil {
  2136. bw = acquireWriter(ctx)
  2137. }
  2138. // Send 'HTTP/1.1 100 Continue' response.
  2139. _, err = bw.Write(strResponseContinue)
  2140. if err != nil {
  2141. break
  2142. }
  2143. err = bw.Flush()
  2144. if err != nil {
  2145. break
  2146. }
  2147. if s.ReduceMemoryUsage {
  2148. releaseWriter(s, bw)
  2149. bw = nil
  2150. }
  2151. // Read request body.
  2152. if br == nil {
  2153. br = acquireReader(ctx)
  2154. }
  2155. if s.StreamRequestBody {
  2156. err = ctx.Request.ContinueReadBodyStream(br, maxRequestBodySize, !s.DisablePreParseMultipartForm)
  2157. } else {
  2158. err = ctx.Request.ContinueReadBody(br, maxRequestBodySize, !s.DisablePreParseMultipartForm)
  2159. }
  2160. if (!s.StreamRequestBody && s.ReduceMemoryUsage && br.Buffered() == 0) || err != nil {
  2161. releaseReader(s, br)
  2162. br = nil
  2163. }
  2164. if err != nil {
  2165. bw = s.writeErrorResponse(bw, ctx, serverName, err)
  2166. break
  2167. }
  2168. }
  2169. }
  2170. // store req.ConnectionClose so even if it was changed inside of handler
  2171. connectionClose = s.DisableKeepalive || ctx.Request.Header.ConnectionClose()
  2172. if serverName != "" {
  2173. ctx.Response.Header.SetServer(serverName)
  2174. }
  2175. ctx.connID = connID
  2176. ctx.connRequestNum = connRequestNum
  2177. ctx.time = time.Now()
  2178. // If a client denies a request the handler should not be called
  2179. if continueReadingRequest {
  2180. s.Handler(ctx)
  2181. }
  2182. timeoutResponse = ctx.timeoutResponse
  2183. if timeoutResponse != nil {
  2184. // Acquire a new ctx because the old one will still be in use by the timeout out handler.
  2185. ctx = s.acquireCtx(c)
  2186. timeoutResponse.CopyTo(&ctx.Response)
  2187. }
  2188. if ctx.IsHead() {
  2189. ctx.Response.SkipBody = true
  2190. }
  2191. hijackHandler = ctx.hijackHandler
  2192. ctx.hijackHandler = nil
  2193. hijackNoResponse = ctx.hijackNoResponse && hijackHandler != nil
  2194. ctx.hijackNoResponse = false
  2195. if writeTimeout > 0 {
  2196. if err = c.SetWriteDeadline(time.Now().Add(writeTimeout)); err != nil {
  2197. break
  2198. }
  2199. previousWriteTimeout = writeTimeout
  2200. } else if previousWriteTimeout > 0 {
  2201. // We don't want a write timeout but we previously set one, remove it.
  2202. if err = c.SetWriteDeadline(zeroTime); err != nil {
  2203. break
  2204. }
  2205. previousWriteTimeout = 0
  2206. }
  2207. connectionClose = connectionClose ||
  2208. (s.MaxRequestsPerConn > 0 && connRequestNum >= uint64(s.MaxRequestsPerConn)) || // #nosec G115
  2209. ctx.Response.Header.ConnectionClose() ||
  2210. (s.CloseOnShutdown && s.stop.Load() == 1)
  2211. if connectionClose {
  2212. ctx.Response.Header.SetConnectionClose()
  2213. } else if !ctx.Request.Header.IsHTTP11() {
  2214. // Set 'Connection: keep-alive' response header for HTTP/1.0 request.
  2215. // There is no need in setting this header for http/1.1, since in http/1.1
  2216. // connections are keep-alive by default.
  2217. ctx.Response.Header.setNonSpecial(strConnection, strKeepAlive)
  2218. }
  2219. if serverName != "" && len(ctx.Response.Header.Server()) == 0 {
  2220. ctx.Response.Header.SetServer(serverName)
  2221. }
  2222. if !hijackNoResponse {
  2223. if bw == nil {
  2224. bw = acquireWriter(ctx)
  2225. }
  2226. if err = writeResponse(ctx, bw); err != nil {
  2227. break
  2228. }
  2229. // Only flush the writer if we don't have another request in the pipeline.
  2230. // This is a big of an ugly optimization for https://www.techempower.com/benchmarks/
  2231. // This benchmark will send 16 pipelined requests. It is faster to pack as many responses
  2232. // in a TCP packet and send it back at once than waiting for a flush every request.
  2233. // In real world circumstances this behaviour could be argued as being wrong.
  2234. if br == nil || br.Buffered() == 0 || connectionClose || (s.ReduceMemoryUsage && hijackHandler == nil) {
  2235. err = bw.Flush()
  2236. if err != nil {
  2237. break
  2238. }
  2239. }
  2240. if connectionClose {
  2241. break
  2242. }
  2243. if s.ReduceMemoryUsage && hijackHandler == nil {
  2244. releaseWriter(s, bw)
  2245. bw = nil
  2246. }
  2247. }
  2248. if hijackHandler != nil {
  2249. var hjr io.Reader = c
  2250. if br != nil {
  2251. hjr = br
  2252. br = nil
  2253. }
  2254. if bw != nil {
  2255. err = bw.Flush()
  2256. if err != nil {
  2257. break
  2258. }
  2259. releaseWriter(s, bw)
  2260. bw = nil
  2261. }
  2262. err = c.SetDeadline(zeroTime)
  2263. if err != nil {
  2264. break
  2265. }
  2266. go hijackConnHandler(ctx, hjr, c, s, hijackHandler)
  2267. err = errHijacked
  2268. break
  2269. }
  2270. if ctx.Request.bodyStream != nil {
  2271. if rs, ok := ctx.Request.bodyStream.(*requestStream); ok {
  2272. releaseRequestStream(rs)
  2273. }
  2274. ctx.Request.bodyStream = nil
  2275. }
  2276. s.setState(c, StateIdle)
  2277. ctx.Request.Reset()
  2278. ctx.Response.Reset()
  2279. if s.stop.Load() == 1 {
  2280. err = nil
  2281. break
  2282. }
  2283. idleConnTime.Store(time.Now().Unix())
  2284. }
  2285. if br != nil {
  2286. releaseReader(s, br)
  2287. }
  2288. if bw != nil {
  2289. releaseWriter(s, bw)
  2290. }
  2291. if hijackHandler == nil {
  2292. s.releaseCtx(ctx)
  2293. }
  2294. s.idleConnsMu.Lock()
  2295. ic, ok := s.idleConns[c]
  2296. if ok {
  2297. idleConnTimePool.Put(ic)
  2298. delete(s.idleConns, c)
  2299. }
  2300. s.idleConnsMu.Unlock()
  2301. return err
  2302. }
  2303. func (s *Server) setState(nc net.Conn, state ConnState) {
  2304. if hook := s.ConnState; hook != nil {
  2305. hook(nc, state)
  2306. }
  2307. }
  2308. func hijackConnHandler(ctx *RequestCtx, r io.Reader, c net.Conn, s *Server, h HijackHandler) {
  2309. hjc := s.acquireHijackConn(r, c)
  2310. h(hjc)
  2311. if br, ok := r.(*bufio.Reader); ok {
  2312. releaseReader(s, br)
  2313. }
  2314. if !s.KeepHijackedConns {
  2315. c.Close()
  2316. s.releaseHijackConn(hjc)
  2317. }
  2318. s.releaseCtx(ctx)
  2319. }
  2320. func (s *Server) acquireHijackConn(r io.Reader, c net.Conn) *hijackConn {
  2321. v := s.hijackConnPool.Get()
  2322. if v == nil {
  2323. hjc := &hijackConn{
  2324. Conn: c,
  2325. r: r,
  2326. s: s,
  2327. }
  2328. return hjc
  2329. }
  2330. hjc := v.(*hijackConn)
  2331. hjc.Conn = c
  2332. hjc.r = r
  2333. return hjc
  2334. }
  2335. func (s *Server) releaseHijackConn(hjc *hijackConn) {
  2336. hjc.Conn = nil
  2337. hjc.r = nil
  2338. s.hijackConnPool.Put(hjc)
  2339. }
  2340. type hijackConn struct {
  2341. net.Conn
  2342. r io.Reader
  2343. s *Server
  2344. }
  2345. func (c *hijackConn) UnsafeConn() net.Conn {
  2346. return c.Conn
  2347. }
  2348. func (c *hijackConn) Read(p []byte) (int, error) {
  2349. return c.r.Read(p)
  2350. }
  2351. func (c *hijackConn) Close() error {
  2352. if !c.s.KeepHijackedConns {
  2353. // when we do not keep hijacked connections,
  2354. // it is closed in hijackConnHandler.
  2355. return nil
  2356. }
  2357. return c.Conn.Close()
  2358. }
  2359. // LastTimeoutErrorResponse returns the last timeout response set
  2360. // via TimeoutError* call.
  2361. //
  2362. // This function is intended for custom server implementations.
  2363. func (ctx *RequestCtx) LastTimeoutErrorResponse() *Response {
  2364. return ctx.timeoutResponse
  2365. }
  2366. func writeResponse(ctx *RequestCtx, w *bufio.Writer) error {
  2367. if ctx.timeoutResponse != nil {
  2368. return errors.New("cannot write timed out response")
  2369. }
  2370. err := ctx.Response.Write(w)
  2371. return err
  2372. }
  2373. const (
  2374. defaultReadBufferSize = 4096
  2375. defaultWriteBufferSize = 4096
  2376. )
  2377. func acquireByteReader(ctxP **RequestCtx) (*bufio.Reader, error) {
  2378. ctx := *ctxP
  2379. s := ctx.s
  2380. c := ctx.c
  2381. s.releaseCtx(ctx)
  2382. //nolint:wastedassign // Make GC happy, so it could garbage collect ctx while we wait for the
  2383. // next request.
  2384. ctx = nil
  2385. *ctxP = nil
  2386. var b [1]byte
  2387. n, err := c.Read(b[:])
  2388. ctx = s.acquireCtx(c)
  2389. *ctxP = ctx
  2390. if err != nil {
  2391. // Treat all errors as EOF on unsuccessful read
  2392. // of the first request byte.
  2393. return nil, io.EOF
  2394. }
  2395. if n != 1 {
  2396. // developer sanity-check
  2397. panic("BUG: Reader must return at least one byte")
  2398. }
  2399. ctx.fbr.c = c
  2400. ctx.fbr.ch = b[0] // #nosec G602
  2401. ctx.fbr.byteRead = false
  2402. r := acquireReader(ctx)
  2403. r.Reset(&ctx.fbr)
  2404. return r, nil
  2405. }
  2406. func acquireReader(ctx *RequestCtx) *bufio.Reader {
  2407. v := ctx.s.readerPool.Get()
  2408. if v == nil {
  2409. n := ctx.s.ReadBufferSize
  2410. if n <= 0 {
  2411. n = defaultReadBufferSize
  2412. }
  2413. return bufio.NewReaderSize(ctx.c, n)
  2414. }
  2415. r := v.(*bufio.Reader)
  2416. r.Reset(ctx.c)
  2417. return r
  2418. }
  2419. func releaseReader(s *Server, r *bufio.Reader) {
  2420. s.readerPool.Put(r)
  2421. }
  2422. func acquireWriter(ctx *RequestCtx) *bufio.Writer {
  2423. v := ctx.s.writerPool.Get()
  2424. if v == nil {
  2425. n := ctx.s.WriteBufferSize
  2426. if n <= 0 {
  2427. n = defaultWriteBufferSize
  2428. }
  2429. return bufio.NewWriterSize(ctx.c, n)
  2430. }
  2431. w := v.(*bufio.Writer)
  2432. w.Reset(ctx.c)
  2433. return w
  2434. }
  2435. func releaseWriter(s *Server, w *bufio.Writer) {
  2436. s.writerPool.Put(w)
  2437. }
  2438. func (s *Server) acquireCtx(c net.Conn) (ctx *RequestCtx) {
  2439. v := s.ctxPool.Get()
  2440. if v == nil {
  2441. keepBodyBuffer := !s.ReduceMemoryUsage
  2442. ctx = new(RequestCtx)
  2443. ctx.Request.keepBodyBuffer = keepBodyBuffer
  2444. ctx.Response.keepBodyBuffer = keepBodyBuffer
  2445. ctx.s = s
  2446. } else {
  2447. ctx = v.(*RequestCtx)
  2448. }
  2449. if s.FormValueFunc != nil {
  2450. ctx.formValueFunc = s.FormValueFunc
  2451. }
  2452. ctx.c = c
  2453. return ctx
  2454. }
  2455. // Init2 prepares ctx for passing to RequestHandler.
  2456. //
  2457. // conn is used only for determining local and remote addresses.
  2458. //
  2459. // This function is intended for custom Server implementations.
  2460. // See https://github.com/valyala/httpteleport for details.
  2461. func (ctx *RequestCtx) Init2(conn net.Conn, logger Logger, reduceMemoryUsage bool) {
  2462. ctx.c = conn
  2463. ctx.remoteAddr = nil
  2464. ctx.logger.logger = logger
  2465. ctx.connID = nextConnID()
  2466. ctx.s = fakeServer
  2467. ctx.connRequestNum = 0
  2468. ctx.connTime = time.Now()
  2469. keepBodyBuffer := !reduceMemoryUsage
  2470. ctx.Request.keepBodyBuffer = keepBodyBuffer
  2471. ctx.Response.keepBodyBuffer = keepBodyBuffer
  2472. }
  2473. // Init prepares ctx for passing to RequestHandler.
  2474. //
  2475. // remoteAddr and logger are optional. They are used by RequestCtx.Logger().
  2476. //
  2477. // This function is intended for custom Server implementations.
  2478. func (ctx *RequestCtx) Init(req *Request, remoteAddr net.Addr, logger Logger) {
  2479. if remoteAddr == nil {
  2480. remoteAddr = zeroTCPAddr
  2481. }
  2482. c := &fakeAddrer{
  2483. laddr: zeroTCPAddr,
  2484. raddr: remoteAddr,
  2485. }
  2486. if logger == nil {
  2487. logger = defaultLogger
  2488. }
  2489. ctx.Init2(c, logger, true)
  2490. req.CopyTo(&ctx.Request)
  2491. }
  2492. // Deadline returns the time when work done on behalf of this context
  2493. // should be canceled. Deadline returns ok==false when no deadline is
  2494. // set. Successive calls to Deadline return the same results.
  2495. //
  2496. // This method always returns 0, false and is only present to make
  2497. // RequestCtx implement the context interface.
  2498. func (ctx *RequestCtx) Deadline() (deadline time.Time, ok bool) {
  2499. return time.Time{}, false
  2500. }
  2501. // Done returns a channel that's closed when work done on behalf of this
  2502. // context should be canceled. Done may return nil if this context can
  2503. // never be canceled. Successive calls to Done return the same value.
  2504. //
  2505. // Note: Because creating a new channel for every request is just too expensive, so
  2506. // RequestCtx.s.done is only closed when the server is shutting down.
  2507. func (ctx *RequestCtx) Done() <-chan struct{} {
  2508. return ctx.s.done
  2509. }
  2510. // Err returns a non-nil error value after Done is closed,
  2511. // successive calls to Err return the same error.
  2512. // If Done is not yet closed, Err returns nil.
  2513. // If Done is closed, Err returns a non-nil error explaining why:
  2514. // Canceled if the context was canceled (via server Shutdown)
  2515. // or DeadlineExceeded if the context's deadline passed.
  2516. //
  2517. // Note: Because creating a new channel for every request is just too expensive, so
  2518. // RequestCtx.s.done is only closed when the server is shutting down.
  2519. func (ctx *RequestCtx) Err() error {
  2520. select {
  2521. case <-ctx.Done():
  2522. return context.Canceled
  2523. default:
  2524. return nil
  2525. }
  2526. }
  2527. // Value returns the value associated with this context for key, or nil
  2528. // if no value is associated with key. Successive calls to Value with
  2529. // the same key returns the same result.
  2530. //
  2531. // This method is present to make RequestCtx implement the context interface.
  2532. // This method is the same as calling ctx.UserValue(key).
  2533. func (ctx *RequestCtx) Value(key any) any {
  2534. return ctx.UserValue(key)
  2535. }
  2536. var fakeServer = &Server{
  2537. done: make(chan struct{}),
  2538. // Initialize concurrencyCh for TimeoutHandler
  2539. concurrencyCh: make(chan struct{}, DefaultConcurrency),
  2540. }
  2541. type fakeAddrer struct {
  2542. net.Conn
  2543. laddr net.Addr
  2544. raddr net.Addr
  2545. }
  2546. func (fa *fakeAddrer) RemoteAddr() net.Addr {
  2547. return fa.raddr
  2548. }
  2549. func (fa *fakeAddrer) LocalAddr() net.Addr {
  2550. return fa.laddr
  2551. }
  2552. func (fa *fakeAddrer) Read(p []byte) (int, error) {
  2553. // developer sanity-check
  2554. panic("BUG: unexpected Read call")
  2555. }
  2556. func (fa *fakeAddrer) Write(p []byte) (int, error) {
  2557. // developer sanity-check
  2558. panic("BUG: unexpected Write call")
  2559. }
  2560. func (fa *fakeAddrer) Close() error {
  2561. // developer sanity-check
  2562. panic("BUG: unexpected Close call")
  2563. }
  2564. func (s *Server) releaseCtx(ctx *RequestCtx) {
  2565. if ctx.timeoutResponse != nil {
  2566. // developer sanity-check
  2567. panic("BUG: cannot release timed out RequestCtx")
  2568. }
  2569. ctx.reset()
  2570. s.ctxPool.Put(ctx)
  2571. }
  2572. func (s *Server) getServerName() string {
  2573. serverName := s.Name
  2574. if serverName == "" {
  2575. if !s.NoDefaultServerHeader {
  2576. serverName = defaultServerName
  2577. }
  2578. }
  2579. return serverName
  2580. }
  2581. func (s *Server) writeFastError(w io.Writer, statusCode int, msg string) {
  2582. w.Write(formatStatusLine(nil, strHTTP11, statusCode, s2b(StatusMessage(statusCode)))) //nolint:errcheck
  2583. server := s.getServerName()
  2584. if server != "" {
  2585. server = fmt.Sprintf("Server: %s\r\n", server)
  2586. }
  2587. date := ""
  2588. if !s.NoDefaultDate {
  2589. serverDateOnce.Do(updateServerDate)
  2590. date = fmt.Sprintf("Date: %s\r\n", serverDate.Load())
  2591. }
  2592. fmt.Fprintf(w, "Connection: close\r\n"+
  2593. server+
  2594. date+
  2595. "Content-Type: text/plain\r\n"+
  2596. "Content-Length: %d\r\n"+
  2597. "\r\n"+
  2598. "%s",
  2599. len(msg), msg)
  2600. }
  2601. func defaultErrorHandler(ctx *RequestCtx, err error) {
  2602. if _, ok := err.(*ErrSmallBuffer); ok {
  2603. ctx.Error("Too big request header", StatusRequestHeaderFieldsTooLarge)
  2604. } else if netErr, ok := err.(*net.OpError); ok && netErr.Timeout() {
  2605. ctx.Error("Request timeout", StatusRequestTimeout)
  2606. } else {
  2607. ctx.Error("Error when parsing request", StatusBadRequest)
  2608. }
  2609. }
  2610. func (s *Server) writeErrorResponse(bw *bufio.Writer, ctx *RequestCtx, serverName string, err error) *bufio.Writer {
  2611. errorHandler := defaultErrorHandler
  2612. if s.ErrorHandler != nil {
  2613. errorHandler = s.ErrorHandler
  2614. }
  2615. errorHandler(ctx, err)
  2616. if serverName != "" {
  2617. ctx.Response.Header.SetServer(serverName)
  2618. }
  2619. ctx.SetConnectionClose()
  2620. if bw == nil {
  2621. bw = acquireWriter(ctx)
  2622. }
  2623. writeResponse(ctx, bw) //nolint:errcheck
  2624. ctx.Response.Reset()
  2625. bw.Flush()
  2626. return bw
  2627. }
  2628. var idleConnTimePool sync.Pool
  2629. func (s *Server) closeIdleConns() {
  2630. s.idleConnsMu.Lock()
  2631. now := time.Now().Unix()
  2632. for c, ict := range s.idleConns {
  2633. t := ict.Load()
  2634. if t != 0 && now-t >= 0 {
  2635. _ = c.Close()
  2636. delete(s.idleConns, c)
  2637. idleConnTimePool.Put(ict)
  2638. }
  2639. }
  2640. s.idleConnsMu.Unlock()
  2641. }
  2642. func (s *Server) closeListenersLocked() error {
  2643. var err error
  2644. for _, ln := range s.ln {
  2645. if cerr := ln.Close(); cerr != nil && err == nil {
  2646. err = cerr
  2647. }
  2648. }
  2649. s.ln = nil
  2650. return err
  2651. }
  2652. // A ConnState represents the state of a client connection to a server.
  2653. // It's used by the optional Server.ConnState hook.
  2654. type ConnState int
  2655. const (
  2656. // StateNew represents a new connection that is expected to
  2657. // send a request immediately. Connections begin at this
  2658. // state and then transition to either StateActive or
  2659. // StateClosed.
  2660. StateNew ConnState = iota
  2661. // StateActive represents a connection that has read 1 or more
  2662. // bytes of a request. The Server.ConnState hook for
  2663. // StateActive fires before the request has entered a handler
  2664. // and doesn't fire again until the request has been
  2665. // handled. After the request is handled, the state
  2666. // transitions to StateClosed, StateHijacked, or StateIdle.
  2667. // For HTTP/2, StateActive fires on the transition from zero
  2668. // to one active request, and only transitions away once all
  2669. // active requests are complete. That means that ConnState
  2670. // cannot be used to do per-request work; ConnState only notes
  2671. // the overall state of the connection.
  2672. StateActive
  2673. // StateIdle represents a connection that has finished
  2674. // handling a request and is in the keep-alive state, waiting
  2675. // for a new request. Connections transition from StateIdle
  2676. // to either StateActive or StateClosed.
  2677. StateIdle
  2678. // StateHijacked represents a hijacked connection.
  2679. // This is a terminal state. It does not transition to StateClosed.
  2680. StateHijacked
  2681. // StateClosed represents a closed connection.
  2682. // This is a terminal state. Hijacked connections do not
  2683. // transition to StateClosed.
  2684. StateClosed
  2685. )
  2686. var stateName = []string{
  2687. StateNew: "new",
  2688. StateActive: "active",
  2689. StateIdle: "idle",
  2690. StateHijacked: "hijacked",
  2691. StateClosed: "closed",
  2692. }
  2693. func (c ConnState) String() string {
  2694. return stateName[c]
  2695. }