server.go 82 KB

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