http.go 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650
  1. package fasthttp
  2. import (
  3. "bufio"
  4. "bytes"
  5. "compress/gzip"
  6. "encoding/base64"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "mime/multipart"
  11. "net"
  12. "os"
  13. "sync"
  14. "time"
  15. "github.com/valyala/bytebufferpool"
  16. )
  17. var (
  18. requestBodyPoolSizeLimit = -1
  19. responseBodyPoolSizeLimit = -1
  20. )
  21. // SetBodySizePoolLimit set the max body size for bodies to be returned to the pool.
  22. // If the body size is larger it will be released instead of put back into the pool for reuse.
  23. func SetBodySizePoolLimit(reqBodyLimit, respBodyLimit int) {
  24. requestBodyPoolSizeLimit = reqBodyLimit
  25. responseBodyPoolSizeLimit = respBodyLimit
  26. }
  27. // Request represents HTTP request.
  28. //
  29. // It is forbidden copying Request instances. Create new instances
  30. // and use CopyTo instead.
  31. //
  32. // Request instance MUST NOT be used from concurrently running goroutines.
  33. type Request struct {
  34. noCopy noCopy
  35. bodyStream io.Reader
  36. w requestBodyWriter
  37. body *bytebufferpool.ByteBuffer
  38. multipartForm *multipart.Form
  39. multipartFormBoundary string
  40. postArgs Args
  41. userValues userData
  42. bodyRaw []byte
  43. uri URI
  44. // Request header.
  45. //
  46. // Copying Header by value is forbidden. Use pointer to Header instead.
  47. Header RequestHeader
  48. // Request timeout. Usually set by DoDeadline or DoTimeout
  49. // if <= 0, means not set
  50. timeout time.Duration
  51. secureErrorLogMessage bool
  52. // Group bool members in order to reduce Request object size.
  53. parsedURI bool
  54. parsedPostArgs bool
  55. keepBodyBuffer bool
  56. // Used by Server to indicate the request was received on a HTTPS endpoint.
  57. // Client/HostClient shouldn't use this field but should depend on the uri.scheme instead.
  58. isTLS bool
  59. // Use Host header (request.Header.SetHost) instead of the host from SetRequestURI, SetHost, or URI().SetHost
  60. UseHostHeader bool
  61. // DisableRedirectPathNormalizing disables redirect path normalization when used with DoRedirects.
  62. //
  63. // By default redirect path values are normalized, i.e.
  64. // extra slashes are removed, special characters are encoded.
  65. DisableRedirectPathNormalizing bool
  66. }
  67. // Response represents HTTP response.
  68. //
  69. // It is forbidden copying Response instances. Create new instances
  70. // and use CopyTo instead.
  71. //
  72. // Response instance MUST NOT be used from concurrently running goroutines.
  73. type Response struct {
  74. noCopy noCopy
  75. bodyStream io.Reader
  76. // Remote TCPAddr from concurrently net.Conn.
  77. raddr net.Addr
  78. // Local TCPAddr from concurrently net.Conn.
  79. laddr net.Addr
  80. w responseBodyWriter
  81. body *bytebufferpool.ByteBuffer
  82. bodyRaw []byte
  83. // Response header.
  84. //
  85. // Copying Header by value is forbidden. Use pointer to Header instead.
  86. Header ResponseHeader
  87. // Flush headers as soon as possible without waiting for first body bytes.
  88. // Relevant for bodyStream only.
  89. ImmediateHeaderFlush bool
  90. // StreamBody enables response body streaming.
  91. // Use SetBodyStream to set the body stream.
  92. StreamBody bool
  93. // Response.Read() skips reading body if set to true.
  94. // Use it for reading HEAD responses.
  95. //
  96. // Response.Write() skips writing body if set to true.
  97. // Use it for writing HEAD responses.
  98. SkipBody bool
  99. keepBodyBuffer bool
  100. secureErrorLogMessage bool
  101. }
  102. // SetHost sets host for the request.
  103. func (req *Request) SetHost(host string) {
  104. req.URI().SetHost(host)
  105. }
  106. // SetHostBytes sets host for the request.
  107. func (req *Request) SetHostBytes(host []byte) {
  108. req.URI().SetHostBytes(host)
  109. }
  110. // Host returns the host for the given request.
  111. func (req *Request) Host() []byte {
  112. return req.URI().Host()
  113. }
  114. // SetRequestURI sets RequestURI.
  115. func (req *Request) SetRequestURI(requestURI string) {
  116. req.Header.SetRequestURI(requestURI)
  117. req.parsedURI = false
  118. }
  119. // SetRequestURIBytes sets RequestURI.
  120. func (req *Request) SetRequestURIBytes(requestURI []byte) {
  121. req.Header.SetRequestURIBytes(requestURI)
  122. req.parsedURI = false
  123. }
  124. // RequestURI returns request's URI.
  125. func (req *Request) RequestURI() []byte {
  126. if req.parsedURI {
  127. requestURI := req.uri.RequestURI()
  128. req.SetRequestURIBytes(requestURI)
  129. }
  130. return req.Header.RequestURI()
  131. }
  132. // StatusCode returns response status code.
  133. func (resp *Response) StatusCode() int {
  134. return resp.Header.StatusCode()
  135. }
  136. // SetStatusCode sets response status code.
  137. func (resp *Response) SetStatusCode(statusCode int) {
  138. resp.Header.SetStatusCode(statusCode)
  139. }
  140. // ConnectionClose returns true if 'Connection: close' header is set.
  141. func (resp *Response) ConnectionClose() bool {
  142. return resp.Header.ConnectionClose()
  143. }
  144. // SetConnectionClose sets 'Connection: close' header.
  145. func (resp *Response) SetConnectionClose() {
  146. resp.Header.SetConnectionClose()
  147. }
  148. // ConnectionClose returns true if 'Connection: close' header is set.
  149. func (req *Request) ConnectionClose() bool {
  150. return req.Header.ConnectionClose()
  151. }
  152. // SetConnectionClose sets 'Connection: close' header.
  153. func (req *Request) SetConnectionClose() {
  154. req.Header.SetConnectionClose()
  155. }
  156. // GetTimeOut retrieves the timeout duration set for the Request.
  157. //
  158. // This method returns a time.Duration that determines how long the request
  159. // can wait before it times out. In the default use case, the timeout applies
  160. // to the entire request lifecycle, including both receiving the response
  161. // headers and the response body.
  162. func (req *Request) GetTimeOut() time.Duration {
  163. return req.timeout
  164. }
  165. // SendFile registers file on the given path to be used as response body
  166. // when Write is called.
  167. //
  168. // Note that SendFile doesn't set Content-Type, so set it yourself
  169. // with Header.SetContentType.
  170. func (resp *Response) SendFile(path string) error {
  171. f, err := os.Open(path)
  172. if err != nil {
  173. return err
  174. }
  175. fileInfo, err := f.Stat()
  176. if err != nil {
  177. f.Close()
  178. return err
  179. }
  180. size64 := fileInfo.Size()
  181. size := int(size64)
  182. if int64(size) != size64 {
  183. size = -1
  184. }
  185. resp.Header.SetLastModified(fileInfo.ModTime())
  186. resp.SetBodyStream(f, size)
  187. return nil
  188. }
  189. // SetBodyStream sets request body stream and, optionally body size.
  190. //
  191. // If bodySize is >= 0, then the bodyStream must provide exactly bodySize bytes
  192. // before returning io.EOF.
  193. //
  194. // If bodySize < 0, then bodyStream is read until io.EOF.
  195. //
  196. // bodyStream.Close() is called after finishing reading all body data
  197. // if it implements io.Closer.
  198. //
  199. // Note that GET and HEAD requests cannot have body.
  200. //
  201. // See also SetBodyStreamWriter.
  202. func (req *Request) SetBodyStream(bodyStream io.Reader, bodySize int) {
  203. req.ResetBody()
  204. req.bodyStream = bodyStream
  205. req.Header.SetContentLength(bodySize)
  206. }
  207. // SetBodyStream sets response body stream and, optionally body size.
  208. //
  209. // If bodySize is >= 0, then the bodyStream must provide exactly bodySize bytes
  210. // before returning io.EOF.
  211. //
  212. // If bodySize < 0, then bodyStream is read until io.EOF.
  213. //
  214. // bodyStream.Close() is called after finishing reading all body data
  215. // if it implements io.Closer.
  216. //
  217. // See also SetBodyStreamWriter.
  218. func (resp *Response) SetBodyStream(bodyStream io.Reader, bodySize int) {
  219. resp.ResetBody()
  220. resp.bodyStream = bodyStream
  221. resp.Header.SetContentLength(bodySize)
  222. }
  223. // IsBodyStream returns true if body is set via SetBodyStream*.
  224. func (req *Request) IsBodyStream() bool {
  225. return req.bodyStream != nil
  226. }
  227. // IsBodyStream returns true if body is set via SetBodyStream*.
  228. func (resp *Response) IsBodyStream() bool {
  229. return resp.bodyStream != nil
  230. }
  231. // SetBodyStreamWriter registers the given sw for populating request body.
  232. //
  233. // This function may be used in the following cases:
  234. //
  235. // - if request body is too big (more than 10MB).
  236. // - if request body is streamed from slow external sources.
  237. // - if request body must be streamed to the server in chunks
  238. // (aka `http client push` or `chunked transfer-encoding`).
  239. //
  240. // Note that GET and HEAD requests cannot have body.
  241. //
  242. // See also SetBodyStream.
  243. func (req *Request) SetBodyStreamWriter(sw StreamWriter) {
  244. sr := NewStreamReader(sw)
  245. req.SetBodyStream(sr, -1)
  246. }
  247. // SetBodyStreamWriter registers the given sw for populating response body.
  248. //
  249. // This function may be used in the following cases:
  250. //
  251. // - if response body is too big (more than 10MB).
  252. // - if response body is streamed from slow external sources.
  253. // - if response body must be streamed to the client in chunks
  254. // (aka `http server push` or `chunked transfer-encoding`).
  255. //
  256. // See also SetBodyStream.
  257. func (resp *Response) SetBodyStreamWriter(sw StreamWriter) {
  258. sr := NewStreamReader(sw)
  259. resp.SetBodyStream(sr, -1)
  260. }
  261. // BodyWriter returns writer for populating response body.
  262. //
  263. // If used inside RequestHandler, the returned writer must not be used
  264. // after returning from RequestHandler. Use RequestCtx.Write
  265. // or SetBodyStreamWriter in this case.
  266. func (resp *Response) BodyWriter() io.Writer {
  267. resp.w.r = resp
  268. return &resp.w
  269. }
  270. // BodyStream returns io.Reader.
  271. //
  272. // You must CloseBodyStream or ReleaseRequest after you use it.
  273. func (req *Request) BodyStream() io.Reader {
  274. return req.bodyStream
  275. }
  276. func (req *Request) CloseBodyStream() error {
  277. return req.closeBodyStream()
  278. }
  279. // BodyStream returns io.Reader.
  280. //
  281. // You must CloseBodyStream or ReleaseResponse after you use it.
  282. func (resp *Response) BodyStream() io.Reader {
  283. return resp.bodyStream
  284. }
  285. func (resp *Response) CloseBodyStream() error {
  286. return resp.closeBodyStream(nil)
  287. }
  288. type ReadCloserWithError interface {
  289. io.Reader
  290. CloseWithError(err error) error
  291. }
  292. type closeReader struct {
  293. io.Reader
  294. closeFunc func(err error) error
  295. }
  296. func newCloseReaderWithError(r io.Reader, closeFunc func(err error) error) ReadCloserWithError {
  297. if r == nil {
  298. panic(`BUG: reader is nil`)
  299. }
  300. return &closeReader{Reader: r, closeFunc: closeFunc}
  301. }
  302. func (c *closeReader) CloseWithError(err error) error {
  303. if c.closeFunc == nil {
  304. return nil
  305. }
  306. return c.closeFunc(err)
  307. }
  308. // BodyWriter returns writer for populating request body.
  309. func (req *Request) BodyWriter() io.Writer {
  310. req.w.r = req
  311. return &req.w
  312. }
  313. type responseBodyWriter struct {
  314. r *Response
  315. }
  316. func (w *responseBodyWriter) Write(p []byte) (int, error) {
  317. w.r.AppendBody(p)
  318. return len(p), nil
  319. }
  320. type requestBodyWriter struct {
  321. r *Request
  322. }
  323. func (w *requestBodyWriter) Write(p []byte) (int, error) {
  324. w.r.AppendBody(p)
  325. return len(p), nil
  326. }
  327. func (resp *Response) ParseNetConn(conn net.Conn) {
  328. resp.raddr = conn.RemoteAddr()
  329. resp.laddr = conn.LocalAddr()
  330. }
  331. // RemoteAddr returns the remote network address. The Addr returned is shared
  332. // by all invocations of RemoteAddr, so do not modify it.
  333. func (resp *Response) RemoteAddr() net.Addr {
  334. return resp.raddr
  335. }
  336. // LocalAddr returns the local network address. The Addr returned is shared
  337. // by all invocations of LocalAddr, so do not modify it.
  338. func (resp *Response) LocalAddr() net.Addr {
  339. return resp.laddr
  340. }
  341. // Body returns response body.
  342. //
  343. // The returned value is valid until the response is released,
  344. // either though ReleaseResponse or your request handler returning.
  345. // Do not store references to returned value. Make copies instead.
  346. func (resp *Response) Body() []byte {
  347. if resp.bodyStream != nil {
  348. bodyBuf := resp.bodyBuffer()
  349. bodyBuf.Reset()
  350. _, err := copyZeroAlloc(bodyBuf, resp.bodyStream)
  351. resp.closeBodyStream(err) //nolint:errcheck
  352. if err != nil {
  353. bodyBuf.SetString(err.Error())
  354. }
  355. }
  356. return resp.bodyBytes()
  357. }
  358. func (resp *Response) bodyBytes() []byte {
  359. if resp.bodyRaw != nil {
  360. return resp.bodyRaw
  361. }
  362. if resp.body == nil {
  363. return nil
  364. }
  365. return resp.body.B
  366. }
  367. func (req *Request) bodyBytes() []byte {
  368. if req.bodyRaw != nil {
  369. return req.bodyRaw
  370. }
  371. if req.bodyStream != nil {
  372. bodyBuf := req.bodyBuffer()
  373. bodyBuf.Reset()
  374. _, err := copyZeroAlloc(bodyBuf, req.bodyStream)
  375. req.closeBodyStream() //nolint:errcheck
  376. if err != nil {
  377. bodyBuf.SetString(err.Error())
  378. }
  379. }
  380. if req.body == nil {
  381. return nil
  382. }
  383. return req.body.B
  384. }
  385. func (resp *Response) bodyBuffer() *bytebufferpool.ByteBuffer {
  386. if resp.body == nil {
  387. resp.body = responseBodyPool.Get()
  388. }
  389. resp.bodyRaw = nil
  390. return resp.body
  391. }
  392. func (req *Request) bodyBuffer() *bytebufferpool.ByteBuffer {
  393. if req.body == nil {
  394. req.body = requestBodyPool.Get()
  395. }
  396. req.bodyRaw = nil
  397. return req.body
  398. }
  399. var (
  400. responseBodyPool bytebufferpool.Pool
  401. requestBodyPool bytebufferpool.Pool
  402. )
  403. // BodyGunzip returns un-gzipped body data.
  404. //
  405. // This method may be used if the request header contains
  406. // 'Content-Encoding: gzip' for reading un-gzipped body.
  407. // Use Body for reading gzipped request body.
  408. func (req *Request) BodyGunzip() ([]byte, error) {
  409. return gunzipData(req.Body())
  410. }
  411. // BodyGunzip returns un-gzipped body data.
  412. //
  413. // This method may be used if the response header contains
  414. // 'Content-Encoding: gzip' for reading un-gzipped body.
  415. // Use Body for reading gzipped response body.
  416. func (resp *Response) BodyGunzip() ([]byte, error) {
  417. return gunzipData(resp.Body())
  418. }
  419. func gunzipData(p []byte) ([]byte, error) {
  420. var bb bytebufferpool.ByteBuffer
  421. _, err := WriteGunzip(&bb, p)
  422. if err != nil {
  423. return nil, err
  424. }
  425. return bb.B, nil
  426. }
  427. // BodyUnbrotli returns un-brotlied body data.
  428. //
  429. // This method may be used if the request header contains
  430. // 'Content-Encoding: br' for reading un-brotlied body.
  431. // Use Body for reading brotlied request body.
  432. func (req *Request) BodyUnbrotli() ([]byte, error) {
  433. return unBrotliData(req.Body())
  434. }
  435. // BodyUnbrotli returns un-brotlied body data.
  436. //
  437. // This method may be used if the response header contains
  438. // 'Content-Encoding: br' for reading un-brotlied body.
  439. // Use Body for reading brotlied response body.
  440. func (resp *Response) BodyUnbrotli() ([]byte, error) {
  441. return unBrotliData(resp.Body())
  442. }
  443. func unBrotliData(p []byte) ([]byte, error) {
  444. var bb bytebufferpool.ByteBuffer
  445. _, err := WriteUnbrotli(&bb, p)
  446. if err != nil {
  447. return nil, err
  448. }
  449. return bb.B, nil
  450. }
  451. // BodyInflate returns inflated body data.
  452. //
  453. // This method may be used if the response header contains
  454. // 'Content-Encoding: deflate' for reading inflated request body.
  455. // Use Body for reading deflated request body.
  456. func (req *Request) BodyInflate() ([]byte, error) {
  457. return inflateData(req.Body())
  458. }
  459. // BodyInflate returns inflated body data.
  460. //
  461. // This method may be used if the response header contains
  462. // 'Content-Encoding: deflate' for reading inflated response body.
  463. // Use Body for reading deflated response body.
  464. func (resp *Response) BodyInflate() ([]byte, error) {
  465. return inflateData(resp.Body())
  466. }
  467. func (ctx *RequestCtx) RequestBodyStream() io.Reader {
  468. return ctx.Request.bodyStream
  469. }
  470. func (req *Request) BodyUnzstd() ([]byte, error) {
  471. return unzstdData(req.Body())
  472. }
  473. func (resp *Response) BodyUnzstd() ([]byte, error) {
  474. return unzstdData(resp.Body())
  475. }
  476. func unzstdData(p []byte) ([]byte, error) {
  477. var bb bytebufferpool.ByteBuffer
  478. _, err := WriteUnzstd(&bb, p)
  479. if err != nil {
  480. return nil, err
  481. }
  482. return bb.B, nil
  483. }
  484. func inflateData(p []byte) ([]byte, error) {
  485. var bb bytebufferpool.ByteBuffer
  486. _, err := WriteInflate(&bb, p)
  487. if err != nil {
  488. return nil, err
  489. }
  490. return bb.B, nil
  491. }
  492. var ErrContentEncodingUnsupported = errors.New("unsupported Content-Encoding")
  493. // BodyUncompressed returns body data and if needed decompress it from gzip, deflate or Brotli.
  494. //
  495. // This method may be used if the response header contains
  496. // 'Content-Encoding' for reading uncompressed request body.
  497. // Use Body for reading the raw request body.
  498. func (req *Request) BodyUncompressed() ([]byte, error) {
  499. switch string(req.Header.ContentEncoding()) {
  500. case "":
  501. return req.Body(), nil
  502. case "deflate":
  503. return req.BodyInflate()
  504. case "gzip":
  505. return req.BodyGunzip()
  506. case "br":
  507. return req.BodyUnbrotli()
  508. case "zstd":
  509. return req.BodyUnzstd()
  510. default:
  511. return nil, ErrContentEncodingUnsupported
  512. }
  513. }
  514. // BodyUncompressed returns body data and if needed decompress it from gzip, deflate or Brotli.
  515. //
  516. // This method may be used if the response header contains
  517. // 'Content-Encoding' for reading uncompressed response body.
  518. // Use Body for reading the raw response body.
  519. func (resp *Response) BodyUncompressed() ([]byte, error) {
  520. switch string(resp.Header.ContentEncoding()) {
  521. case "":
  522. return resp.Body(), nil
  523. case "deflate":
  524. return resp.BodyInflate()
  525. case "gzip":
  526. return resp.BodyGunzip()
  527. case "br":
  528. return resp.BodyUnbrotli()
  529. case "zstd":
  530. return resp.BodyUnzstd()
  531. default:
  532. return nil, ErrContentEncodingUnsupported
  533. }
  534. }
  535. // BodyWriteTo writes request body to w.
  536. func (req *Request) BodyWriteTo(w io.Writer) error {
  537. if req.bodyStream != nil {
  538. _, err := copyZeroAlloc(w, req.bodyStream)
  539. req.closeBodyStream() //nolint:errcheck
  540. return err
  541. }
  542. if req.onlyMultipartForm() {
  543. return WriteMultipartForm(w, req.multipartForm, req.multipartFormBoundary)
  544. }
  545. _, err := w.Write(req.bodyBytes())
  546. return err
  547. }
  548. // BodyWriteTo writes response body to w.
  549. func (resp *Response) BodyWriteTo(w io.Writer) error {
  550. if resp.bodyStream != nil {
  551. _, err := copyZeroAlloc(w, resp.bodyStream)
  552. resp.closeBodyStream(err) //nolint:errcheck
  553. return err
  554. }
  555. _, err := w.Write(resp.bodyBytes())
  556. return err
  557. }
  558. // AppendBody appends p to response body.
  559. //
  560. // It is safe re-using p after the function returns.
  561. func (resp *Response) AppendBody(p []byte) {
  562. resp.closeBodyStream(nil) //nolint:errcheck
  563. resp.bodyBuffer().Write(p) //nolint:errcheck
  564. }
  565. // AppendBodyString appends s to response body.
  566. func (resp *Response) AppendBodyString(s string) {
  567. resp.closeBodyStream(nil) //nolint:errcheck
  568. resp.bodyBuffer().WriteString(s) //nolint:errcheck
  569. }
  570. // SetBody sets response body.
  571. //
  572. // It is safe re-using body argument after the function returns.
  573. func (resp *Response) SetBody(body []byte) {
  574. resp.closeBodyStream(nil) //nolint:errcheck
  575. bodyBuf := resp.bodyBuffer()
  576. bodyBuf.Reset()
  577. bodyBuf.Write(body) //nolint:errcheck
  578. }
  579. // SetBodyString sets response body.
  580. func (resp *Response) SetBodyString(body string) {
  581. resp.closeBodyStream(nil) //nolint:errcheck
  582. bodyBuf := resp.bodyBuffer()
  583. bodyBuf.Reset()
  584. bodyBuf.WriteString(body) //nolint:errcheck
  585. }
  586. // ResetBody resets response body.
  587. func (resp *Response) ResetBody() {
  588. resp.bodyRaw = nil
  589. resp.closeBodyStream(nil) //nolint:errcheck
  590. if resp.body != nil {
  591. if resp.keepBodyBuffer {
  592. resp.body.Reset()
  593. } else {
  594. responseBodyPool.Put(resp.body)
  595. resp.body = nil
  596. }
  597. }
  598. }
  599. // SetBodyRaw sets response body, but without copying it.
  600. //
  601. // From this point onward the body argument must not be changed.
  602. func (resp *Response) SetBodyRaw(body []byte) {
  603. resp.ResetBody()
  604. resp.bodyRaw = body
  605. }
  606. // SetBodyRaw sets response body, but without copying it.
  607. //
  608. // From this point onward the body argument must not be changed.
  609. func (req *Request) SetBodyRaw(body []byte) {
  610. req.ResetBody()
  611. req.bodyRaw = body
  612. }
  613. // ReleaseBody retires the response body if it is greater than "size" bytes.
  614. //
  615. // This permits GC to reclaim the large buffer. If used, must be before
  616. // ReleaseResponse.
  617. //
  618. // Use this method only if you really understand how it works.
  619. // The majority of workloads don't need this method.
  620. func (resp *Response) ReleaseBody(size int) {
  621. resp.bodyRaw = nil
  622. if resp.body == nil {
  623. return
  624. }
  625. if cap(resp.body.B) > size {
  626. resp.closeBodyStream(nil) //nolint:errcheck
  627. resp.body = nil
  628. }
  629. }
  630. // ReleaseBody retires the request body if it is greater than "size" bytes.
  631. //
  632. // This permits GC to reclaim the large buffer. If used, must be before
  633. // ReleaseRequest.
  634. //
  635. // Use this method only if you really understand how it works.
  636. // The majority of workloads don't need this method.
  637. func (req *Request) ReleaseBody(size int) {
  638. req.bodyRaw = nil
  639. if req.body == nil {
  640. return
  641. }
  642. if cap(req.body.B) > size {
  643. req.closeBodyStream() //nolint:errcheck
  644. req.body = nil
  645. }
  646. }
  647. // SwapBody swaps response body with the given body and returns
  648. // the previous response body.
  649. //
  650. // It is forbidden to use the body passed to SwapBody after
  651. // the function returns.
  652. func (resp *Response) SwapBody(body []byte) []byte {
  653. bb := resp.bodyBuffer()
  654. if resp.bodyStream != nil {
  655. bb.Reset()
  656. _, err := copyZeroAlloc(bb, resp.bodyStream)
  657. resp.closeBodyStream(err) //nolint:errcheck
  658. if err != nil {
  659. bb.Reset()
  660. bb.SetString(err.Error())
  661. }
  662. }
  663. resp.bodyRaw = nil
  664. oldBody := bb.B
  665. bb.B = body
  666. return oldBody
  667. }
  668. // SwapBody swaps request body with the given body and returns
  669. // the previous request body.
  670. //
  671. // It is forbidden to use the body passed to SwapBody after
  672. // the function returns.
  673. func (req *Request) SwapBody(body []byte) []byte {
  674. bb := req.bodyBuffer()
  675. if req.bodyStream != nil {
  676. bb.Reset()
  677. _, err := copyZeroAlloc(bb, req.bodyStream)
  678. req.closeBodyStream() //nolint:errcheck
  679. if err != nil {
  680. bb.Reset()
  681. bb.SetString(err.Error())
  682. }
  683. }
  684. req.bodyRaw = nil
  685. oldBody := bb.B
  686. bb.B = body
  687. return oldBody
  688. }
  689. // Body returns request body.
  690. //
  691. // The returned value is valid until the request is released,
  692. // either though ReleaseRequest or your request handler returning.
  693. // Do not store references to returned value. Make copies instead.
  694. func (req *Request) Body() []byte {
  695. if req.bodyRaw != nil {
  696. return req.bodyRaw
  697. } else if req.onlyMultipartForm() {
  698. body, err := marshalMultipartForm(req.multipartForm, req.multipartFormBoundary)
  699. if err != nil {
  700. return []byte(err.Error())
  701. }
  702. return body
  703. }
  704. return req.bodyBytes()
  705. }
  706. // AppendBody appends p to request body.
  707. //
  708. // It is safe re-using p after the function returns.
  709. func (req *Request) AppendBody(p []byte) {
  710. req.RemoveMultipartFormFiles()
  711. req.closeBodyStream() //nolint:errcheck
  712. req.bodyBuffer().Write(p) //nolint:errcheck
  713. }
  714. // AppendBodyString appends s to request body.
  715. func (req *Request) AppendBodyString(s string) {
  716. req.RemoveMultipartFormFiles()
  717. req.closeBodyStream() //nolint:errcheck
  718. req.bodyBuffer().WriteString(s) //nolint:errcheck
  719. }
  720. // SetBody sets request body.
  721. //
  722. // It is safe re-using body argument after the function returns.
  723. func (req *Request) SetBody(body []byte) {
  724. req.RemoveMultipartFormFiles()
  725. req.closeBodyStream() //nolint:errcheck
  726. req.bodyBuffer().Set(body)
  727. }
  728. // SetBodyString sets request body.
  729. func (req *Request) SetBodyString(body string) {
  730. req.RemoveMultipartFormFiles()
  731. req.closeBodyStream() //nolint:errcheck
  732. req.bodyBuffer().SetString(body)
  733. }
  734. // ResetBody resets request body.
  735. func (req *Request) ResetBody() {
  736. req.bodyRaw = nil
  737. req.RemoveMultipartFormFiles()
  738. req.closeBodyStream() //nolint:errcheck
  739. if req.body != nil {
  740. if req.keepBodyBuffer {
  741. req.body.Reset()
  742. } else {
  743. requestBodyPool.Put(req.body)
  744. req.body = nil
  745. }
  746. }
  747. }
  748. // CopyTo copies req contents to dst except of body stream.
  749. func (req *Request) CopyTo(dst *Request) {
  750. req.copyToSkipBody(dst)
  751. switch {
  752. case req.bodyRaw != nil:
  753. dst.bodyRaw = append(dst.bodyRaw[:0], req.bodyRaw...)
  754. if dst.body != nil {
  755. dst.body.Reset()
  756. }
  757. case req.body != nil:
  758. dst.bodyBuffer().Set(req.body.B)
  759. case dst.body != nil:
  760. dst.body.Reset()
  761. }
  762. }
  763. func (req *Request) copyToSkipBody(dst *Request) {
  764. dst.Reset()
  765. req.Header.CopyTo(&dst.Header)
  766. req.uri.CopyTo(&dst.uri)
  767. dst.parsedURI = req.parsedURI
  768. req.postArgs.CopyTo(&dst.postArgs)
  769. dst.parsedPostArgs = req.parsedPostArgs
  770. dst.isTLS = req.isTLS
  771. dst.UseHostHeader = req.UseHostHeader
  772. // do not copy multipartForm - it will be automatically
  773. // re-created on the first call to MultipartForm.
  774. }
  775. // CopyTo copies resp contents to dst except of body stream.
  776. func (resp *Response) CopyTo(dst *Response) {
  777. resp.copyToSkipBody(dst)
  778. switch {
  779. case resp.bodyRaw != nil:
  780. dst.bodyRaw = append(dst.bodyRaw, resp.bodyRaw...)
  781. if dst.body != nil {
  782. dst.body.Reset()
  783. }
  784. case resp.body != nil:
  785. dst.bodyBuffer().Set(resp.body.B)
  786. case dst.body != nil:
  787. dst.body.Reset()
  788. }
  789. }
  790. func (resp *Response) copyToSkipBody(dst *Response) {
  791. dst.Reset()
  792. resp.Header.CopyTo(&dst.Header)
  793. dst.SkipBody = resp.SkipBody
  794. dst.raddr = resp.raddr
  795. dst.laddr = resp.laddr
  796. }
  797. func swapRequestBody(a, b *Request) {
  798. a.body, b.body = b.body, a.body
  799. a.bodyRaw, b.bodyRaw = b.bodyRaw, a.bodyRaw
  800. a.bodyStream, b.bodyStream = b.bodyStream, a.bodyStream
  801. // This code assumes that if a requestStream was swapped the headers are also swapped or copied.
  802. if rs, ok := a.bodyStream.(*requestStream); ok {
  803. rs.header = &a.Header
  804. }
  805. if rs, ok := b.bodyStream.(*requestStream); ok {
  806. rs.header = &b.Header
  807. }
  808. }
  809. func swapResponseBody(a, b *Response) {
  810. a.body, b.body = b.body, a.body
  811. a.bodyRaw, b.bodyRaw = b.bodyRaw, a.bodyRaw
  812. a.bodyStream, b.bodyStream = b.bodyStream, a.bodyStream
  813. }
  814. // URI returns request URI.
  815. func (req *Request) URI() *URI {
  816. req.parseURI() //nolint:errcheck
  817. return &req.uri
  818. }
  819. // SetURI initializes request URI.
  820. // Use this method if a single URI may be reused across multiple requests.
  821. // Otherwise, you can just use SetRequestURI() and it will be parsed as new URI.
  822. // The URI is copied and can be safely modified later.
  823. func (req *Request) SetURI(newURI *URI) {
  824. if newURI != nil {
  825. newURI.CopyTo(&req.uri)
  826. req.parsedURI = true
  827. return
  828. }
  829. req.uri.Reset()
  830. req.parsedURI = false
  831. }
  832. func (req *Request) parseURI() error {
  833. if req.parsedURI {
  834. return nil
  835. }
  836. req.parsedURI = true
  837. return req.uri.parse(req.Header.Host(), req.Header.RequestURI(), req.isTLS)
  838. }
  839. // PostArgs returns POST arguments.
  840. func (req *Request) PostArgs() *Args {
  841. req.parsePostArgs()
  842. return &req.postArgs
  843. }
  844. func (req *Request) parsePostArgs() {
  845. if req.parsedPostArgs {
  846. return
  847. }
  848. req.parsedPostArgs = true
  849. if !bytes.HasPrefix(req.Header.ContentType(), strPostArgsContentType) {
  850. return
  851. }
  852. req.postArgs.ParseBytes(req.bodyBytes())
  853. }
  854. // ErrNoMultipartForm means that the request's Content-Type
  855. // isn't 'multipart/form-data'.
  856. var ErrNoMultipartForm = errors.New("request Content-Type has bad boundary or is not multipart/form-data")
  857. // MultipartForm returns request's multipart form.
  858. //
  859. // Returns ErrNoMultipartForm if request's Content-Type
  860. // isn't 'multipart/form-data'.
  861. //
  862. // RemoveMultipartFormFiles must be called after returned multipart form
  863. // is processed.
  864. func (req *Request) MultipartForm() (*multipart.Form, error) {
  865. if req.multipartForm != nil {
  866. return req.multipartForm, nil
  867. }
  868. req.multipartFormBoundary = string(req.Header.MultipartFormBoundary())
  869. if req.multipartFormBoundary == "" {
  870. return nil, ErrNoMultipartForm
  871. }
  872. var err error
  873. ce := req.Header.peek(strContentEncoding)
  874. if req.bodyStream != nil {
  875. bodyStream := req.bodyStream
  876. if bytes.Equal(ce, strGzip) {
  877. // Do not care about memory usage here.
  878. if bodyStream, err = gzip.NewReader(bodyStream); err != nil {
  879. return nil, fmt.Errorf("cannot gunzip request body: %w", err)
  880. }
  881. } else if len(ce) > 0 {
  882. return nil, fmt.Errorf("unsupported Content-Encoding: %q", ce)
  883. }
  884. mr := multipart.NewReader(bodyStream, req.multipartFormBoundary)
  885. req.multipartForm, err = mr.ReadForm(8 * 1024)
  886. if err != nil {
  887. return nil, fmt.Errorf("cannot read multipart/form-data body: %w", err)
  888. }
  889. } else {
  890. body := req.bodyBytes()
  891. if bytes.Equal(ce, strGzip) {
  892. // Do not care about memory usage here.
  893. if body, err = AppendGunzipBytes(nil, body); err != nil {
  894. return nil, fmt.Errorf("cannot gunzip request body: %w", err)
  895. }
  896. } else if len(ce) > 0 {
  897. return nil, fmt.Errorf("unsupported Content-Encoding: %q", ce)
  898. }
  899. req.multipartForm, err = readMultipartForm(bytes.NewReader(body), req.multipartFormBoundary, len(body), len(body))
  900. if err != nil {
  901. return nil, err
  902. }
  903. }
  904. return req.multipartForm, nil
  905. }
  906. func marshalMultipartForm(f *multipart.Form, boundary string) ([]byte, error) {
  907. var buf bytebufferpool.ByteBuffer
  908. if err := WriteMultipartForm(&buf, f, boundary); err != nil {
  909. return nil, err
  910. }
  911. return buf.B, nil
  912. }
  913. // WriteMultipartForm writes the given multipart form f with the given
  914. // boundary to w.
  915. func WriteMultipartForm(w io.Writer, f *multipart.Form, boundary string) error {
  916. // Do not care about memory allocations here, since multipart
  917. // form processing is slow.
  918. if boundary == "" {
  919. return errors.New("form boundary cannot be empty")
  920. }
  921. mw := multipart.NewWriter(w)
  922. if err := mw.SetBoundary(boundary); err != nil {
  923. return fmt.Errorf("cannot use form boundary %q: %w", boundary, err)
  924. }
  925. // marshal values
  926. for k, vv := range f.Value {
  927. for _, v := range vv {
  928. if err := mw.WriteField(k, v); err != nil {
  929. return fmt.Errorf("cannot write form field %q value %q: %w", k, v, err)
  930. }
  931. }
  932. }
  933. // marshal files
  934. for k, fvv := range f.File {
  935. for _, fv := range fvv {
  936. vw, err := mw.CreatePart(fv.Header)
  937. if err != nil {
  938. return fmt.Errorf("cannot create form file %q (%q): %w", k, fv.Filename, err)
  939. }
  940. fh, err := fv.Open()
  941. if err != nil {
  942. return fmt.Errorf("cannot open form file %q (%q): %w", k, fv.Filename, err)
  943. }
  944. if _, err = copyZeroAlloc(vw, fh); err != nil {
  945. _ = fh.Close()
  946. return fmt.Errorf("error when copying form file %q (%q): %w", k, fv.Filename, err)
  947. }
  948. if err = fh.Close(); err != nil {
  949. return fmt.Errorf("cannot close form file %q (%q): %w", k, fv.Filename, err)
  950. }
  951. }
  952. }
  953. if err := mw.Close(); err != nil {
  954. return fmt.Errorf("error when closing multipart form writer: %w", err)
  955. }
  956. return nil
  957. }
  958. func readMultipartForm(r io.Reader, boundary string, size, maxInMemoryFileSize int) (*multipart.Form, error) {
  959. // Do not care about memory allocations here, since they are tiny
  960. // compared to multipart data (aka multi-MB files) usually sent
  961. // in multipart/form-data requests.
  962. if size <= 0 {
  963. return nil, fmt.Errorf("form size must be greater than 0. Given %d", size)
  964. }
  965. lr := io.LimitReader(r, int64(size))
  966. mr := multipart.NewReader(lr, boundary)
  967. f, err := mr.ReadForm(int64(maxInMemoryFileSize))
  968. if err != nil {
  969. return nil, fmt.Errorf("cannot read multipart/form-data body: %w", err)
  970. }
  971. return f, nil
  972. }
  973. // Reset clears request contents.
  974. func (req *Request) Reset() {
  975. req.userValues.Reset() // it should be at the top, since some values might implement io.Closer interface
  976. if requestBodyPoolSizeLimit >= 0 && req.body != nil {
  977. req.ReleaseBody(requestBodyPoolSizeLimit)
  978. }
  979. req.Header.Reset()
  980. req.resetSkipHeader()
  981. req.timeout = 0
  982. req.UseHostHeader = false
  983. req.DisableRedirectPathNormalizing = false
  984. }
  985. func (req *Request) resetSkipHeader() {
  986. req.ResetBody()
  987. req.uri.Reset()
  988. req.parsedURI = false
  989. req.postArgs.Reset()
  990. req.parsedPostArgs = false
  991. req.isTLS = false
  992. }
  993. // RemoveMultipartFormFiles removes multipart/form-data temporary files
  994. // associated with the request.
  995. func (req *Request) RemoveMultipartFormFiles() {
  996. if req.multipartForm != nil {
  997. // Do not check for error, since these files may be deleted or moved
  998. // to new places by user code.
  999. req.multipartForm.RemoveAll() //nolint:errcheck
  1000. req.multipartForm = nil
  1001. }
  1002. req.multipartFormBoundary = ""
  1003. }
  1004. // Reset clears response contents.
  1005. func (resp *Response) Reset() {
  1006. if responseBodyPoolSizeLimit >= 0 && resp.body != nil {
  1007. resp.ReleaseBody(responseBodyPoolSizeLimit)
  1008. }
  1009. resp.resetSkipHeader()
  1010. resp.Header.Reset()
  1011. resp.SkipBody = false
  1012. resp.raddr = nil
  1013. resp.laddr = nil
  1014. resp.ImmediateHeaderFlush = false
  1015. resp.StreamBody = false
  1016. }
  1017. func (resp *Response) resetSkipHeader() {
  1018. resp.ResetBody()
  1019. }
  1020. // Read reads request (including body) from the given r.
  1021. //
  1022. // RemoveMultipartFormFiles or Reset must be called after
  1023. // reading multipart/form-data request in order to delete temporarily
  1024. // uploaded files.
  1025. //
  1026. // If MayContinue returns true, the caller must:
  1027. //
  1028. // - Either send StatusExpectationFailed response if request headers don't
  1029. // satisfy the caller.
  1030. // - Or send StatusContinue response before reading request body
  1031. // with ContinueReadBody.
  1032. // - Or close the connection.
  1033. //
  1034. // io.EOF is returned if r is closed before reading the first header byte.
  1035. func (req *Request) Read(r *bufio.Reader) error {
  1036. return req.ReadLimitBody(r, 0)
  1037. }
  1038. const defaultMaxInMemoryFileSize = 16 * 1024 * 1024
  1039. // ErrGetOnly is returned when server expects only GET requests,
  1040. // but some other type of request came (Server.GetOnly option is true).
  1041. var ErrGetOnly = errors.New("non-GET request received")
  1042. // ReadLimitBody reads request from the given r, limiting the body size.
  1043. //
  1044. // If maxBodySize > 0 and the body size exceeds maxBodySize,
  1045. // then ErrBodyTooLarge is returned.
  1046. //
  1047. // RemoveMultipartFormFiles or Reset must be called after
  1048. // reading multipart/form-data request in order to delete temporarily
  1049. // uploaded files.
  1050. //
  1051. // If MayContinue returns true, the caller must:
  1052. //
  1053. // - Either send StatusExpectationFailed response if request headers don't
  1054. // satisfy the caller.
  1055. // - Or send StatusContinue response before reading request body
  1056. // with ContinueReadBody.
  1057. // - Or close the connection.
  1058. //
  1059. // io.EOF is returned if r is closed before reading the first header byte.
  1060. func (req *Request) ReadLimitBody(r *bufio.Reader, maxBodySize int) error {
  1061. req.resetSkipHeader()
  1062. if err := req.Header.Read(r); err != nil {
  1063. return err
  1064. }
  1065. return req.readLimitBody(r, maxBodySize, false, true)
  1066. }
  1067. func (req *Request) readLimitBody(r *bufio.Reader, maxBodySize int, getOnly, preParseMultipartForm bool) error {
  1068. // Do not reset the request here - the caller must reset it before
  1069. // calling this method.
  1070. if getOnly && !req.Header.IsGet() && !req.Header.IsHead() {
  1071. return ErrGetOnly
  1072. }
  1073. if req.MayContinue() {
  1074. // 'Expect: 100-continue' header found. Let the caller deciding
  1075. // whether to read request body or
  1076. // to return StatusExpectationFailed.
  1077. return nil
  1078. }
  1079. return req.ContinueReadBody(r, maxBodySize, preParseMultipartForm)
  1080. }
  1081. func (req *Request) readBodyStream(r *bufio.Reader, maxBodySize int, getOnly, preParseMultipartForm bool) error {
  1082. // Do not reset the request here - the caller must reset it before
  1083. // calling this method.
  1084. if getOnly && !req.Header.IsGet() && !req.Header.IsHead() {
  1085. return ErrGetOnly
  1086. }
  1087. if req.MayContinue() {
  1088. // 'Expect: 100-continue' header found. Let the caller deciding
  1089. // whether to read request body or
  1090. // to return StatusExpectationFailed.
  1091. return nil
  1092. }
  1093. return req.ContinueReadBodyStream(r, maxBodySize, preParseMultipartForm)
  1094. }
  1095. // MayContinue returns true if the request contains
  1096. // 'Expect: 100-continue' header.
  1097. //
  1098. // The caller must do one of the following actions if MayContinue returns true:
  1099. //
  1100. // - Either send StatusExpectationFailed response if request headers don't
  1101. // satisfy the caller.
  1102. // - Or send StatusContinue response before reading request body
  1103. // with ContinueReadBody.
  1104. // - Or close the connection.
  1105. func (req *Request) MayContinue() bool {
  1106. return bytes.Equal(req.Header.peek(strExpect), str100Continue)
  1107. }
  1108. // ContinueReadBody reads request body if request header contains
  1109. // 'Expect: 100-continue'.
  1110. //
  1111. // The caller must send StatusContinue response before calling this method.
  1112. //
  1113. // If maxBodySize > 0 and the body size exceeds maxBodySize,
  1114. // then ErrBodyTooLarge is returned.
  1115. func (req *Request) ContinueReadBody(r *bufio.Reader, maxBodySize int, preParseMultipartForm ...bool) error {
  1116. var err error
  1117. contentLength := req.Header.realContentLength()
  1118. if contentLength > 0 {
  1119. if maxBodySize > 0 && contentLength > maxBodySize {
  1120. return ErrBodyTooLarge
  1121. }
  1122. if len(preParseMultipartForm) == 0 || preParseMultipartForm[0] {
  1123. // Pre-read multipart form data of known length.
  1124. // This way we limit memory usage for large file uploads, since their contents
  1125. // is streamed into temporary files if file size exceeds defaultMaxInMemoryFileSize.
  1126. req.multipartFormBoundary = string(req.Header.MultipartFormBoundary())
  1127. if req.multipartFormBoundary != "" && len(req.Header.peek(strContentEncoding)) == 0 {
  1128. req.multipartForm, err = readMultipartForm(r, req.multipartFormBoundary, contentLength, defaultMaxInMemoryFileSize)
  1129. if err != nil {
  1130. req.Reset()
  1131. }
  1132. return err
  1133. }
  1134. }
  1135. }
  1136. if contentLength == -2 {
  1137. // identity body has no sense for http requests, since
  1138. // the end of body is determined by connection close.
  1139. // So just ignore request body for requests without
  1140. // 'Content-Length' and 'Transfer-Encoding' headers.
  1141. // refer to https://tools.ietf.org/html/rfc7230#section-3.3.2
  1142. if !req.Header.ignoreBody() {
  1143. req.Header.SetContentLength(0)
  1144. }
  1145. return nil
  1146. }
  1147. if err = req.ReadBody(r, contentLength, maxBodySize); err != nil {
  1148. return err
  1149. }
  1150. if contentLength == -1 {
  1151. err = req.Header.ReadTrailer(r)
  1152. if err != nil && err != io.EOF {
  1153. return err
  1154. }
  1155. }
  1156. return nil
  1157. }
  1158. // ReadBody reads request body from the given r, limiting the body size.
  1159. //
  1160. // If maxBodySize > 0 and the body size exceeds maxBodySize,
  1161. // then ErrBodyTooLarge is returned.
  1162. func (req *Request) ReadBody(r *bufio.Reader, contentLength, maxBodySize int) (err error) {
  1163. bodyBuf := req.bodyBuffer()
  1164. bodyBuf.Reset()
  1165. switch {
  1166. case contentLength >= 0:
  1167. bodyBuf.B, err = readBody(r, contentLength, maxBodySize, bodyBuf.B)
  1168. case contentLength == -1:
  1169. bodyBuf.B, err = readBodyChunked(r, maxBodySize, bodyBuf.B)
  1170. if err == nil && len(bodyBuf.B) == 0 {
  1171. req.Header.SetContentLength(0)
  1172. }
  1173. default:
  1174. bodyBuf.B, err = readBodyIdentity(r, maxBodySize, bodyBuf.B)
  1175. req.Header.SetContentLength(len(bodyBuf.B))
  1176. }
  1177. if err != nil {
  1178. req.Reset()
  1179. return err
  1180. }
  1181. return nil
  1182. }
  1183. // ContinueReadBodyStream reads request body if request header contains
  1184. // 'Expect: 100-continue'.
  1185. //
  1186. // The caller must send StatusContinue response before calling this method.
  1187. //
  1188. // If maxBodySize > 0 and the body size exceeds maxBodySize,
  1189. // then ErrBodyTooLarge is returned.
  1190. func (req *Request) ContinueReadBodyStream(r *bufio.Reader, maxBodySize int, preParseMultipartForm ...bool) error {
  1191. var err error
  1192. contentLength := req.Header.realContentLength()
  1193. if contentLength > 0 {
  1194. if len(preParseMultipartForm) == 0 || preParseMultipartForm[0] {
  1195. // Pre-read multipart form data of known length.
  1196. // This way we limit memory usage for large file uploads, since their contents
  1197. // is streamed into temporary files if file size exceeds defaultMaxInMemoryFileSize.
  1198. req.multipartFormBoundary = b2s(req.Header.MultipartFormBoundary())
  1199. if req.multipartFormBoundary != "" && len(req.Header.peek(strContentEncoding)) == 0 {
  1200. req.multipartForm, err = readMultipartForm(r, req.multipartFormBoundary, contentLength, defaultMaxInMemoryFileSize)
  1201. if err != nil {
  1202. req.Reset()
  1203. }
  1204. return err
  1205. }
  1206. }
  1207. }
  1208. if contentLength == -2 {
  1209. // identity body has no sense for http requests, since
  1210. // the end of body is determined by connection close.
  1211. // So just ignore request body for requests without
  1212. // 'Content-Length' and 'Transfer-Encoding' headers.
  1213. // refer to https://tools.ietf.org/html/rfc7230#section-3.3.2
  1214. if !req.Header.ignoreBody() {
  1215. req.Header.SetContentLength(0)
  1216. }
  1217. return nil
  1218. }
  1219. bodyBuf := req.bodyBuffer()
  1220. bodyBuf.Reset()
  1221. bodyBuf.B, err = readBodyWithStreaming(r, contentLength, maxBodySize, bodyBuf.B)
  1222. if err != nil {
  1223. if err == ErrBodyTooLarge {
  1224. req.Header.SetContentLength(contentLength)
  1225. req.body = bodyBuf
  1226. req.bodyStream = acquireRequestStream(bodyBuf, r, &req.Header)
  1227. return nil
  1228. }
  1229. if err == errChunkedStream {
  1230. req.body = bodyBuf
  1231. req.bodyStream = acquireRequestStream(bodyBuf, r, &req.Header)
  1232. return nil
  1233. }
  1234. req.Reset()
  1235. return err
  1236. }
  1237. req.body = bodyBuf
  1238. req.bodyStream = acquireRequestStream(bodyBuf, r, &req.Header)
  1239. req.Header.SetContentLength(contentLength)
  1240. return nil
  1241. }
  1242. // Read reads response (including body) from the given r.
  1243. //
  1244. // io.EOF is returned if r is closed before reading the first header byte.
  1245. func (resp *Response) Read(r *bufio.Reader) error {
  1246. return resp.ReadLimitBody(r, 0)
  1247. }
  1248. // ReadLimitBody reads response headers from the given r,
  1249. // then reads the body using the ReadBody function and limiting the body size.
  1250. //
  1251. // If resp.SkipBody is true then it skips reading the response body.
  1252. //
  1253. // If maxBodySize > 0 and the body size exceeds maxBodySize,
  1254. // then ErrBodyTooLarge is returned.
  1255. //
  1256. // io.EOF is returned if r is closed before reading the first header byte.
  1257. func (resp *Response) ReadLimitBody(r *bufio.Reader, maxBodySize int) error {
  1258. resp.resetSkipHeader()
  1259. err := resp.Header.Read(r)
  1260. if err != nil {
  1261. return err
  1262. }
  1263. if resp.Header.StatusCode() == StatusContinue {
  1264. // Read the next response according to http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html .
  1265. if err = resp.Header.Read(r); err != nil {
  1266. return err
  1267. }
  1268. }
  1269. if !resp.mustSkipBody() {
  1270. err = resp.ReadBody(r, maxBodySize)
  1271. if err != nil {
  1272. return err
  1273. }
  1274. }
  1275. // A response without a body can't have trailers.
  1276. if resp.Header.ContentLength() == -1 && !resp.StreamBody && !resp.mustSkipBody() {
  1277. err = resp.Header.ReadTrailer(r)
  1278. if err != nil && err != io.EOF {
  1279. return err
  1280. }
  1281. }
  1282. return nil
  1283. }
  1284. // ReadBody reads response body from the given r, limiting the body size.
  1285. //
  1286. // If maxBodySize > 0 and the body size exceeds maxBodySize,
  1287. // then ErrBodyTooLarge is returned.
  1288. func (resp *Response) ReadBody(r *bufio.Reader, maxBodySize int) (err error) {
  1289. bodyBuf := resp.bodyBuffer()
  1290. bodyBuf.Reset()
  1291. contentLength := resp.Header.ContentLength()
  1292. switch {
  1293. case contentLength >= 0:
  1294. bodyBuf.B, err = readBody(r, contentLength, maxBodySize, bodyBuf.B)
  1295. if err == ErrBodyTooLarge && resp.StreamBody {
  1296. resp.bodyStream = acquireRequestStream(bodyBuf, r, &resp.Header)
  1297. err = nil
  1298. }
  1299. case contentLength == -1:
  1300. if resp.StreamBody {
  1301. resp.bodyStream = acquireRequestStream(bodyBuf, r, &resp.Header)
  1302. } else {
  1303. bodyBuf.B, err = readBodyChunked(r, maxBodySize, bodyBuf.B)
  1304. }
  1305. default:
  1306. if resp.StreamBody {
  1307. resp.bodyStream = acquireRequestStream(bodyBuf, r, &resp.Header)
  1308. } else {
  1309. bodyBuf.B, err = readBodyIdentity(r, maxBodySize, bodyBuf.B)
  1310. resp.Header.SetContentLength(len(bodyBuf.B))
  1311. }
  1312. }
  1313. if err == nil && resp.StreamBody && resp.bodyStream == nil {
  1314. resp.bodyStream = bytes.NewReader(bodyBuf.B)
  1315. }
  1316. return err
  1317. }
  1318. func (resp *Response) mustSkipBody() bool {
  1319. return resp.SkipBody || resp.Header.mustSkipContentLength()
  1320. }
  1321. var errRequestHostRequired = errors.New("missing required Host header in request")
  1322. // WriteTo writes request to w. It implements io.WriterTo.
  1323. func (req *Request) WriteTo(w io.Writer) (int64, error) {
  1324. return writeBufio(req, w)
  1325. }
  1326. // WriteTo writes response to w. It implements io.WriterTo.
  1327. func (resp *Response) WriteTo(w io.Writer) (int64, error) {
  1328. return writeBufio(resp, w)
  1329. }
  1330. func writeBufio(hw httpWriter, w io.Writer) (int64, error) {
  1331. sw := acquireStatsWriter(w)
  1332. bw := acquireBufioWriter(sw)
  1333. errw := hw.Write(bw)
  1334. errf := bw.Flush()
  1335. releaseBufioWriter(bw)
  1336. n := sw.bytesWritten
  1337. releaseStatsWriter(sw)
  1338. err := errw
  1339. if err == nil {
  1340. err = errf
  1341. }
  1342. return n, err
  1343. }
  1344. type statsWriter struct {
  1345. w io.Writer
  1346. bytesWritten int64
  1347. }
  1348. func (w *statsWriter) Write(p []byte) (int, error) {
  1349. n, err := w.w.Write(p)
  1350. w.bytesWritten += int64(n)
  1351. return n, err
  1352. }
  1353. func acquireStatsWriter(w io.Writer) *statsWriter {
  1354. v := statsWriterPool.Get()
  1355. if v == nil {
  1356. return &statsWriter{
  1357. w: w,
  1358. }
  1359. }
  1360. sw := v.(*statsWriter)
  1361. sw.w = w
  1362. return sw
  1363. }
  1364. func releaseStatsWriter(sw *statsWriter) {
  1365. sw.w = nil
  1366. sw.bytesWritten = 0
  1367. statsWriterPool.Put(sw)
  1368. }
  1369. var statsWriterPool sync.Pool
  1370. func acquireBufioWriter(w io.Writer) *bufio.Writer {
  1371. v := bufioWriterPool.Get()
  1372. if v == nil {
  1373. return bufio.NewWriter(w)
  1374. }
  1375. bw := v.(*bufio.Writer)
  1376. bw.Reset(w)
  1377. return bw
  1378. }
  1379. func releaseBufioWriter(bw *bufio.Writer) {
  1380. bufioWriterPool.Put(bw)
  1381. }
  1382. var bufioWriterPool sync.Pool
  1383. func (req *Request) onlyMultipartForm() bool {
  1384. return req.multipartForm != nil && (req.body == nil || len(req.body.B) == 0)
  1385. }
  1386. // Write writes request to w.
  1387. //
  1388. // Write doesn't flush request to w for performance reasons.
  1389. //
  1390. // See also WriteTo.
  1391. func (req *Request) Write(w *bufio.Writer) error {
  1392. if len(req.Header.Host()) == 0 || req.parsedURI {
  1393. uri := req.URI()
  1394. host := uri.Host()
  1395. if len(req.Header.Host()) == 0 {
  1396. if len(host) == 0 {
  1397. return errRequestHostRequired
  1398. }
  1399. req.Header.SetHostBytes(host)
  1400. } else if !req.UseHostHeader {
  1401. req.Header.SetHostBytes(host)
  1402. }
  1403. req.Header.SetRequestURIBytes(uri.RequestURI())
  1404. if len(uri.username) > 0 {
  1405. // RequestHeader.SetBytesKV only uses RequestHeader.bufKV.key
  1406. // So we are free to use RequestHeader.bufKV.value as a scratch pad for
  1407. // the base64 encoding.
  1408. nl := len(uri.username) + len(uri.password) + 1
  1409. nb := nl + len(strBasicSpace)
  1410. tl := nb + base64.StdEncoding.EncodedLen(nl)
  1411. if tl > cap(req.Header.bufV) {
  1412. req.Header.bufV = make([]byte, 0, tl)
  1413. }
  1414. buf := req.Header.bufV[:0]
  1415. buf = append(buf, uri.username...)
  1416. buf = append(buf, strColon...)
  1417. buf = append(buf, uri.password...)
  1418. buf = append(buf, strBasicSpace...)
  1419. base64.StdEncoding.Encode(buf[nb:tl], buf[:nl])
  1420. req.Header.SetBytesKV(strAuthorization, buf[nl:tl])
  1421. }
  1422. }
  1423. if req.bodyStream != nil {
  1424. return req.writeBodyStream(w)
  1425. }
  1426. body := req.bodyBytes()
  1427. var err error
  1428. if req.onlyMultipartForm() {
  1429. body, err = marshalMultipartForm(req.multipartForm, req.multipartFormBoundary)
  1430. if err != nil {
  1431. return fmt.Errorf("error when marshaling multipart form: %w", err)
  1432. }
  1433. req.Header.SetMultipartFormBoundary(req.multipartFormBoundary)
  1434. }
  1435. hasBody := false
  1436. if len(body) == 0 {
  1437. body = req.postArgs.QueryString()
  1438. }
  1439. if len(body) != 0 || !req.Header.ignoreBody() {
  1440. hasBody = true
  1441. req.Header.SetContentLength(len(body))
  1442. }
  1443. if err = req.Header.Write(w); err != nil {
  1444. return err
  1445. }
  1446. if hasBody {
  1447. _, err = w.Write(body)
  1448. } else if len(body) > 0 {
  1449. if req.secureErrorLogMessage {
  1450. return errors.New("non-zero body for non-POST request")
  1451. }
  1452. return fmt.Errorf("non-zero body for non-POST request. body=%q", body)
  1453. }
  1454. return err
  1455. }
  1456. // WriteGzip writes response with gzipped body to w.
  1457. //
  1458. // The method gzips response body and sets 'Content-Encoding: gzip'
  1459. // header before writing response to w.
  1460. //
  1461. // WriteGzip doesn't flush response to w for performance reasons.
  1462. func (resp *Response) WriteGzip(w *bufio.Writer) error {
  1463. return resp.WriteGzipLevel(w, CompressDefaultCompression)
  1464. }
  1465. // WriteGzipLevel writes response with gzipped body to w.
  1466. //
  1467. // Level is the desired compression level:
  1468. //
  1469. // - CompressNoCompression
  1470. // - CompressBestSpeed
  1471. // - CompressBestCompression
  1472. // - CompressDefaultCompression
  1473. // - CompressHuffmanOnly
  1474. //
  1475. // The method gzips response body and sets 'Content-Encoding: gzip'
  1476. // header before writing response to w.
  1477. //
  1478. // WriteGzipLevel doesn't flush response to w for performance reasons.
  1479. func (resp *Response) WriteGzipLevel(w *bufio.Writer, level int) error {
  1480. resp.gzipBody(level)
  1481. return resp.Write(w)
  1482. }
  1483. // WriteDeflate writes response with deflated body to w.
  1484. //
  1485. // The method deflates response body and sets 'Content-Encoding: deflate'
  1486. // header before writing response to w.
  1487. //
  1488. // WriteDeflate doesn't flush response to w for performance reasons.
  1489. func (resp *Response) WriteDeflate(w *bufio.Writer) error {
  1490. return resp.WriteDeflateLevel(w, CompressDefaultCompression)
  1491. }
  1492. // WriteDeflateLevel writes response with deflated body to w.
  1493. //
  1494. // Level is the desired compression level:
  1495. //
  1496. // - CompressNoCompression
  1497. // - CompressBestSpeed
  1498. // - CompressBestCompression
  1499. // - CompressDefaultCompression
  1500. // - CompressHuffmanOnly
  1501. //
  1502. // The method deflates response body and sets 'Content-Encoding: deflate'
  1503. // header before writing response to w.
  1504. //
  1505. // WriteDeflateLevel doesn't flush response to w for performance reasons.
  1506. func (resp *Response) WriteDeflateLevel(w *bufio.Writer, level int) error {
  1507. resp.deflateBody(level)
  1508. return resp.Write(w)
  1509. }
  1510. func (resp *Response) brotliBody(level int) {
  1511. if len(resp.Header.ContentEncoding()) > 0 {
  1512. // It looks like the body is already compressed.
  1513. // Do not compress it again.
  1514. return
  1515. }
  1516. if !resp.Header.isCompressibleContentType() {
  1517. // The content-type cannot be compressed.
  1518. return
  1519. }
  1520. if resp.bodyStream != nil {
  1521. // Reset Content-Length to -1, since it is impossible
  1522. // to determine body size beforehand of streamed compression.
  1523. // For https://github.com/valyala/fasthttp/issues/176 .
  1524. resp.Header.SetContentLength(-1)
  1525. // Do not care about memory allocations here, since brotli is slow
  1526. // and allocates a lot of memory by itself.
  1527. bs := resp.bodyStream
  1528. resp.bodyStream = NewStreamReader(func(sw *bufio.Writer) {
  1529. zw := acquireStacklessBrotliWriter(sw, level)
  1530. fw := &flushWriter{
  1531. wf: zw,
  1532. bw: sw,
  1533. }
  1534. _, wErr := copyZeroAlloc(fw, bs)
  1535. releaseStacklessBrotliWriter(zw, level)
  1536. switch v := bs.(type) {
  1537. case io.Closer:
  1538. v.Close()
  1539. case ReadCloserWithError:
  1540. v.CloseWithError(wErr) //nolint:errcheck
  1541. }
  1542. })
  1543. } else {
  1544. bodyBytes := resp.bodyBytes()
  1545. if len(bodyBytes) < minCompressLen {
  1546. // There is no sense in spending CPU time on small body compression,
  1547. // since there is a very high probability that the compressed
  1548. // body size will be bigger than the original body size.
  1549. return
  1550. }
  1551. w := responseBodyPool.Get()
  1552. w.B = AppendBrotliBytesLevel(w.B, bodyBytes, level)
  1553. // Hack: swap resp.body with w.
  1554. if resp.body != nil {
  1555. responseBodyPool.Put(resp.body)
  1556. }
  1557. resp.body = w
  1558. resp.bodyRaw = nil
  1559. }
  1560. resp.Header.SetContentEncodingBytes(strBr)
  1561. resp.Header.addVaryBytes(strAcceptEncoding)
  1562. }
  1563. func (resp *Response) gzipBody(level int) {
  1564. if len(resp.Header.ContentEncoding()) > 0 {
  1565. // It looks like the body is already compressed.
  1566. // Do not compress it again.
  1567. return
  1568. }
  1569. if !resp.Header.isCompressibleContentType() {
  1570. // The content-type cannot be compressed.
  1571. return
  1572. }
  1573. if resp.bodyStream != nil {
  1574. // Reset Content-Length to -1, since it is impossible
  1575. // to determine body size beforehand of streamed compression.
  1576. // For https://github.com/valyala/fasthttp/issues/176 .
  1577. resp.Header.SetContentLength(-1)
  1578. // Do not care about memory allocations here, since gzip is slow
  1579. // and allocates a lot of memory by itself.
  1580. bs := resp.bodyStream
  1581. resp.bodyStream = NewStreamReader(func(sw *bufio.Writer) {
  1582. zw := acquireStacklessGzipWriter(sw, level)
  1583. fw := &flushWriter{
  1584. wf: zw,
  1585. bw: sw,
  1586. }
  1587. _, wErr := copyZeroAlloc(fw, bs)
  1588. releaseStacklessGzipWriter(zw, level)
  1589. switch v := bs.(type) {
  1590. case io.Closer:
  1591. v.Close()
  1592. case ReadCloserWithError:
  1593. v.CloseWithError(wErr) //nolint:errcheck
  1594. }
  1595. })
  1596. } else {
  1597. bodyBytes := resp.bodyBytes()
  1598. if len(bodyBytes) < minCompressLen {
  1599. // There is no sense in spending CPU time on small body compression,
  1600. // since there is a very high probability that the compressed
  1601. // body size will be bigger than the original body size.
  1602. return
  1603. }
  1604. w := responseBodyPool.Get()
  1605. w.B = AppendGzipBytesLevel(w.B, bodyBytes, level)
  1606. // Hack: swap resp.body with w.
  1607. if resp.body != nil {
  1608. responseBodyPool.Put(resp.body)
  1609. }
  1610. resp.body = w
  1611. resp.bodyRaw = nil
  1612. }
  1613. resp.Header.SetContentEncodingBytes(strGzip)
  1614. resp.Header.addVaryBytes(strAcceptEncoding)
  1615. }
  1616. func (resp *Response) deflateBody(level int) {
  1617. if len(resp.Header.ContentEncoding()) > 0 {
  1618. // It looks like the body is already compressed.
  1619. // Do not compress it again.
  1620. return
  1621. }
  1622. if !resp.Header.isCompressibleContentType() {
  1623. // The content-type cannot be compressed.
  1624. return
  1625. }
  1626. if resp.bodyStream != nil {
  1627. // Reset Content-Length to -1, since it is impossible
  1628. // to determine body size beforehand of streamed compression.
  1629. // For https://github.com/valyala/fasthttp/issues/176 .
  1630. resp.Header.SetContentLength(-1)
  1631. // Do not care about memory allocations here, since flate is slow
  1632. // and allocates a lot of memory by itself.
  1633. bs := resp.bodyStream
  1634. resp.bodyStream = NewStreamReader(func(sw *bufio.Writer) {
  1635. zw := acquireStacklessDeflateWriter(sw, level)
  1636. fw := &flushWriter{
  1637. wf: zw,
  1638. bw: sw,
  1639. }
  1640. _, wErr := copyZeroAlloc(fw, bs)
  1641. releaseStacklessDeflateWriter(zw, level)
  1642. switch v := bs.(type) {
  1643. case io.Closer:
  1644. v.Close()
  1645. case ReadCloserWithError:
  1646. v.CloseWithError(wErr) //nolint:errcheck
  1647. }
  1648. })
  1649. } else {
  1650. bodyBytes := resp.bodyBytes()
  1651. if len(bodyBytes) < minCompressLen {
  1652. // There is no sense in spending CPU time on small body compression,
  1653. // since there is a very high probability that the compressed
  1654. // body size will be bigger than the original body size.
  1655. return
  1656. }
  1657. w := responseBodyPool.Get()
  1658. w.B = AppendDeflateBytesLevel(w.B, bodyBytes, level)
  1659. // Hack: swap resp.body with w.
  1660. if resp.body != nil {
  1661. responseBodyPool.Put(resp.body)
  1662. }
  1663. resp.body = w
  1664. resp.bodyRaw = nil
  1665. }
  1666. resp.Header.SetContentEncodingBytes(strDeflate)
  1667. resp.Header.addVaryBytes(strAcceptEncoding)
  1668. }
  1669. func (resp *Response) zstdBody(level int) {
  1670. if len(resp.Header.ContentEncoding()) > 0 {
  1671. return
  1672. }
  1673. if !resp.Header.isCompressibleContentType() {
  1674. return
  1675. }
  1676. if resp.bodyStream != nil {
  1677. // Reset Content-Length to -1, since it is impossible
  1678. // to determine body size beforehand of streamed compression.
  1679. // For
  1680. resp.Header.SetContentLength(-1)
  1681. // Do not care about memory allocations here, since flate is slow
  1682. // and allocates a lot of memory by itself.
  1683. bs := resp.bodyStream
  1684. resp.bodyStream = NewStreamReader(func(sw *bufio.Writer) {
  1685. zw := acquireStacklessZstdWriter(sw, level)
  1686. fw := &flushWriter{
  1687. wf: zw,
  1688. bw: sw,
  1689. }
  1690. _, wErr := copyZeroAlloc(fw, bs)
  1691. releaseStacklessZstdWriter(zw, level)
  1692. switch v := bs.(type) {
  1693. case io.Closer:
  1694. v.Close()
  1695. case ReadCloserWithError:
  1696. v.CloseWithError(wErr) //nolint:errcheck
  1697. }
  1698. })
  1699. } else {
  1700. bodyBytes := resp.bodyBytes()
  1701. if len(bodyBytes) < minCompressLen {
  1702. return
  1703. }
  1704. w := responseBodyPool.Get()
  1705. w.B = AppendZstdBytesLevel(w.B, bodyBytes, level)
  1706. if resp.body != nil {
  1707. responseBodyPool.Put(resp.body)
  1708. }
  1709. resp.body = w
  1710. resp.bodyRaw = nil
  1711. }
  1712. resp.Header.SetContentEncodingBytes(strZstd)
  1713. resp.Header.addVaryBytes(strAcceptEncoding)
  1714. }
  1715. // Bodies with sizes smaller than minCompressLen aren't compressed at all.
  1716. const minCompressLen = 200
  1717. type writeFlusher interface {
  1718. io.Writer
  1719. Flush() error
  1720. }
  1721. type flushWriter struct {
  1722. wf writeFlusher
  1723. bw *bufio.Writer
  1724. }
  1725. func (w *flushWriter) Write(p []byte) (int, error) {
  1726. n, err := w.wf.Write(p)
  1727. if err != nil {
  1728. return 0, err
  1729. }
  1730. if err = w.wf.Flush(); err != nil {
  1731. return 0, err
  1732. }
  1733. if err = w.bw.Flush(); err != nil {
  1734. return 0, err
  1735. }
  1736. return n, nil
  1737. }
  1738. // Write writes response to w.
  1739. //
  1740. // Write doesn't flush response to w for performance reasons.
  1741. //
  1742. // See also WriteTo.
  1743. func (resp *Response) Write(w *bufio.Writer) error {
  1744. sendBody := !resp.mustSkipBody()
  1745. if resp.bodyStream != nil {
  1746. return resp.writeBodyStream(w, sendBody)
  1747. }
  1748. body := resp.bodyBytes()
  1749. bodyLen := len(body)
  1750. if sendBody || bodyLen > 0 {
  1751. resp.Header.SetContentLength(bodyLen)
  1752. }
  1753. if err := resp.Header.Write(w); err != nil {
  1754. return err
  1755. }
  1756. if sendBody {
  1757. if _, err := w.Write(body); err != nil {
  1758. return err
  1759. }
  1760. }
  1761. return nil
  1762. }
  1763. func (req *Request) writeBodyStream(w *bufio.Writer) error {
  1764. var err error
  1765. contentLength := req.Header.ContentLength()
  1766. if contentLength < 0 {
  1767. lrSize := limitedReaderSize(req.bodyStream)
  1768. if lrSize >= 0 {
  1769. contentLength = int(lrSize)
  1770. if int64(contentLength) != lrSize {
  1771. contentLength = -1
  1772. }
  1773. if contentLength >= 0 {
  1774. req.Header.SetContentLength(contentLength)
  1775. }
  1776. }
  1777. }
  1778. if contentLength >= 0 {
  1779. if err = req.Header.Write(w); err == nil {
  1780. err = writeBodyFixedSize(w, req.bodyStream, int64(contentLength))
  1781. }
  1782. } else {
  1783. req.Header.SetContentLength(-1)
  1784. err = req.Header.Write(w)
  1785. if err == nil {
  1786. err = writeBodyChunked(w, req.bodyStream)
  1787. }
  1788. if err == nil {
  1789. err = req.Header.writeTrailer(w)
  1790. }
  1791. }
  1792. errc := req.closeBodyStream()
  1793. if err == nil {
  1794. err = errc
  1795. }
  1796. return err
  1797. }
  1798. // ErrBodyStreamWritePanic is returned when panic happens during writing body stream.
  1799. type ErrBodyStreamWritePanic struct {
  1800. error
  1801. }
  1802. func (resp *Response) writeBodyStream(w *bufio.Writer, sendBody bool) (err error) {
  1803. defer func() {
  1804. if r := recover(); r != nil {
  1805. err = &ErrBodyStreamWritePanic{
  1806. error: fmt.Errorf("panic while writing body stream: %+v", r),
  1807. }
  1808. }
  1809. }()
  1810. contentLength := resp.Header.ContentLength()
  1811. if contentLength < 0 {
  1812. lrSize := limitedReaderSize(resp.bodyStream)
  1813. if lrSize >= 0 {
  1814. contentLength = int(lrSize)
  1815. if int64(contentLength) != lrSize {
  1816. contentLength = -1
  1817. }
  1818. if contentLength >= 0 {
  1819. resp.Header.SetContentLength(contentLength)
  1820. }
  1821. }
  1822. }
  1823. if contentLength >= 0 {
  1824. if err = resp.Header.Write(w); err == nil {
  1825. if resp.ImmediateHeaderFlush {
  1826. err = w.Flush()
  1827. }
  1828. if err == nil && sendBody {
  1829. err = writeBodyFixedSize(w, resp.bodyStream, int64(contentLength))
  1830. }
  1831. }
  1832. } else {
  1833. resp.Header.SetContentLength(-1)
  1834. if err = resp.Header.Write(w); err == nil {
  1835. if resp.ImmediateHeaderFlush {
  1836. err = w.Flush()
  1837. }
  1838. if err == nil && sendBody {
  1839. err = writeBodyChunked(w, resp.bodyStream)
  1840. }
  1841. if err == nil {
  1842. err = resp.Header.writeTrailer(w)
  1843. }
  1844. }
  1845. }
  1846. errc := resp.closeBodyStream(err)
  1847. if err == nil {
  1848. err = errc
  1849. }
  1850. return err
  1851. }
  1852. func (req *Request) closeBodyStream() error {
  1853. if req.bodyStream == nil {
  1854. return nil
  1855. }
  1856. var err error
  1857. if bsc, ok := req.bodyStream.(io.Closer); ok {
  1858. err = bsc.Close()
  1859. }
  1860. if rs, ok := req.bodyStream.(*requestStream); ok {
  1861. releaseRequestStream(rs)
  1862. }
  1863. req.bodyStream = nil
  1864. return err
  1865. }
  1866. func (resp *Response) closeBodyStream(wErr error) error {
  1867. if resp.bodyStream == nil {
  1868. return nil
  1869. }
  1870. var err error
  1871. if bsc, ok := resp.bodyStream.(io.Closer); ok {
  1872. err = bsc.Close()
  1873. }
  1874. if bsc, ok := resp.bodyStream.(ReadCloserWithError); ok {
  1875. err = bsc.CloseWithError(wErr)
  1876. }
  1877. if bsr, ok := resp.bodyStream.(*requestStream); ok {
  1878. releaseRequestStream(bsr)
  1879. }
  1880. resp.bodyStream = nil
  1881. return err
  1882. }
  1883. // String returns request representation.
  1884. //
  1885. // Returns error message instead of request representation on error.
  1886. //
  1887. // Use Write instead of String for performance-critical code.
  1888. func (req *Request) String() string {
  1889. return getHTTPString(req)
  1890. }
  1891. // String returns response representation.
  1892. //
  1893. // Returns error message instead of response representation on error.
  1894. //
  1895. // Use Write instead of String for performance-critical code.
  1896. func (resp *Response) String() string {
  1897. return getHTTPString(resp)
  1898. }
  1899. // SetUserValue stores the given value (arbitrary object)
  1900. // under the given key in Request.
  1901. //
  1902. // The value stored in Request may be obtained by UserValue*.
  1903. //
  1904. // This functionality may be useful for passing arbitrary values between
  1905. // functions involved in request processing.
  1906. //
  1907. // All the values are removed from Request after returning from the top
  1908. // RequestHandler. Additionally, Close method is called on each value
  1909. // implementing io.Closer before removing the value from Request.
  1910. func (req *Request) SetUserValue(key, value any) {
  1911. req.userValues.Set(key, value)
  1912. }
  1913. // SetUserValueBytes stores the given value (arbitrary object)
  1914. // under the given key in Request.
  1915. //
  1916. // The value stored in Request may be obtained by UserValue*.
  1917. //
  1918. // This functionality may be useful for passing arbitrary values between
  1919. // functions involved in request processing.
  1920. //
  1921. // All the values stored in Request are deleted after returning from RequestHandler.
  1922. func (req *Request) SetUserValueBytes(key []byte, value any) {
  1923. req.userValues.SetBytes(key, value)
  1924. }
  1925. // UserValue returns the value stored via SetUserValue* under the given key.
  1926. func (req *Request) UserValue(key any) any {
  1927. return req.userValues.Get(key)
  1928. }
  1929. // UserValueBytes returns the value stored via SetUserValue*
  1930. // under the given key.
  1931. func (req *Request) UserValueBytes(key []byte) any {
  1932. return req.userValues.GetBytes(key)
  1933. }
  1934. // VisitUserValues calls visitor for each existing userValue with a key that is a string or []byte.
  1935. //
  1936. // visitor must not retain references to key and value after returning.
  1937. // Make key and/or value copies if you need storing them after returning.
  1938. func (req *Request) VisitUserValues(visitor func([]byte, any)) {
  1939. for i, n := 0, len(req.userValues); i < n; i++ {
  1940. kv := &req.userValues[i]
  1941. if _, ok := kv.key.(string); ok {
  1942. visitor(s2b(kv.key.(string)), kv.value)
  1943. }
  1944. }
  1945. }
  1946. // VisitUserValuesAll calls visitor for each existing userValue.
  1947. //
  1948. // visitor must not retain references to key and value after returning.
  1949. // Make key and/or value copies if you need storing them after returning.
  1950. func (req *Request) VisitUserValuesAll(visitor func(any, any)) {
  1951. for i, n := 0, len(req.userValues); i < n; i++ {
  1952. kv := &req.userValues[i]
  1953. visitor(kv.key, kv.value)
  1954. }
  1955. }
  1956. // ResetUserValues allows to reset user values from Request Context.
  1957. func (req *Request) ResetUserValues() {
  1958. req.userValues.Reset()
  1959. }
  1960. // RemoveUserValue removes the given key and the value under it in Request.
  1961. func (req *Request) RemoveUserValue(key any) {
  1962. req.userValues.Remove(key)
  1963. }
  1964. // RemoveUserValueBytes removes the given key and the value under it in Request.
  1965. func (req *Request) RemoveUserValueBytes(key []byte) {
  1966. req.userValues.RemoveBytes(key)
  1967. }
  1968. func getHTTPString(hw httpWriter) string {
  1969. w := bytebufferpool.Get()
  1970. defer bytebufferpool.Put(w)
  1971. bw := bufio.NewWriter(w)
  1972. if err := hw.Write(bw); err != nil {
  1973. return err.Error()
  1974. }
  1975. if err := bw.Flush(); err != nil {
  1976. return err.Error()
  1977. }
  1978. s := string(w.B)
  1979. return s
  1980. }
  1981. type httpWriter interface {
  1982. Write(w *bufio.Writer) error
  1983. }
  1984. func writeBodyChunked(w *bufio.Writer, r io.Reader) error {
  1985. vbuf := copyBufPool.Get()
  1986. buf := vbuf.([]byte)
  1987. var err error
  1988. var n int
  1989. for {
  1990. n, err = r.Read(buf)
  1991. if n == 0 {
  1992. if err == nil {
  1993. continue
  1994. }
  1995. if err == io.EOF {
  1996. if err = writeChunk(w, buf[:0]); err != nil {
  1997. break
  1998. }
  1999. err = nil
  2000. }
  2001. break
  2002. }
  2003. if err = writeChunk(w, buf[:n]); err != nil {
  2004. break
  2005. }
  2006. }
  2007. copyBufPool.Put(vbuf)
  2008. return err
  2009. }
  2010. func limitedReaderSize(r io.Reader) int64 {
  2011. lr, ok := r.(*io.LimitedReader)
  2012. if !ok {
  2013. return -1
  2014. }
  2015. return lr.N
  2016. }
  2017. func writeBodyFixedSize(w *bufio.Writer, r io.Reader, size int64) error {
  2018. if size > maxSmallFileSize {
  2019. earlyFlush := false
  2020. switch r := r.(type) {
  2021. case *os.File:
  2022. earlyFlush = true
  2023. case *io.LimitedReader:
  2024. _, earlyFlush = r.R.(*os.File)
  2025. }
  2026. if earlyFlush {
  2027. // w buffer must be empty for triggering
  2028. // sendfile path in bufio.Writer.ReadFrom.
  2029. if err := w.Flush(); err != nil {
  2030. return err
  2031. }
  2032. }
  2033. }
  2034. n, err := copyZeroAlloc(w, r)
  2035. if n != size && err == nil {
  2036. err = fmt.Errorf("copied %d bytes from body stream instead of %d bytes", n, size)
  2037. }
  2038. return err
  2039. }
  2040. // copyZeroAlloc optimizes io.Copy by calling ReadFrom or WriteTo only when
  2041. // copying between os.File and net.TCPConn. If the reader has a WriteTo
  2042. // method, it uses WriteTo for copying; if the writer has a ReadFrom method,
  2043. // it uses ReadFrom for copying. If neither method is available, it gets a
  2044. // buffer from sync.Pool to perform the copy.
  2045. //
  2046. // io.CopyBuffer always uses the WriterTo or ReadFrom interface if it's
  2047. // available. however, os.File and net.TCPConn unfortunately have a
  2048. // fallback in their WriterTo that calls io.Copy if sendfile isn't possible.
  2049. //
  2050. // See issue: https://github.com/valyala/fasthttp/issues/1889
  2051. //
  2052. // sendfile can only be triggered when copying between os.File and net.TCPConn.
  2053. // Since the function confirming zero-copy is a private function, we use
  2054. // ReadFrom only in this specific scenario. For all other cases, we prioritize
  2055. // using our own copyBuffer method.
  2056. //
  2057. // o: our copyBuffer
  2058. // r: readFrom
  2059. // w: writeTo
  2060. //
  2061. // write\read *File *TCPConn writeTo other
  2062. // *File o r w o
  2063. // *TCPConn w,r o w o
  2064. // readFrom r r w r
  2065. // other o o w o
  2066. //
  2067. //nolint:dupword
  2068. func copyZeroAlloc(w io.Writer, r io.Reader) (int64, error) {
  2069. var readerIsFile, readerIsConn bool
  2070. switch r := r.(type) {
  2071. case *os.File:
  2072. readerIsFile = true
  2073. case *net.TCPConn:
  2074. readerIsConn = true
  2075. case io.WriterTo:
  2076. return r.WriteTo(w)
  2077. }
  2078. switch w := w.(type) {
  2079. case *os.File:
  2080. if readerIsConn {
  2081. return w.ReadFrom(r)
  2082. }
  2083. case *net.TCPConn:
  2084. if readerIsFile {
  2085. // net.WriteTo requires go1.22 or later
  2086. // Benchmark tests show that on Windows, WriteTo performs
  2087. // significantly better than ReadFrom. On Linux, however,
  2088. // ReadFrom slightly outperforms WriteTo. When possible,
  2089. // copyZeroAlloc aims to perform better than or as well
  2090. // as io.Copy, so we use WriteTo whenever possible for
  2091. // optimal performance.
  2092. if rt, ok := r.(io.WriterTo); ok {
  2093. return rt.WriteTo(w)
  2094. }
  2095. return w.ReadFrom(r)
  2096. }
  2097. case io.ReaderFrom:
  2098. return w.ReadFrom(r)
  2099. }
  2100. vbuf := copyBufPool.Get()
  2101. buf := vbuf.([]byte)
  2102. n, err := copyBuffer(w, r, buf)
  2103. copyBufPool.Put(vbuf)
  2104. return n, err
  2105. }
  2106. // copyBuffer is rewritten from io.copyBuffer. We do not check if src has a
  2107. // WriteTo method, if dst has a ReadFrom method, or if buf is empty.
  2108. func copyBuffer(dst io.Writer, src io.Reader, buf []byte) (written int64, err error) {
  2109. for {
  2110. nr, er := src.Read(buf)
  2111. if nr > 0 {
  2112. nw, ew := dst.Write(buf[0:nr])
  2113. if nw < 0 || nr < nw {
  2114. nw = 0
  2115. if ew == nil {
  2116. ew = errors.New("invalid write result")
  2117. }
  2118. }
  2119. written += int64(nw)
  2120. if ew != nil {
  2121. err = ew
  2122. break
  2123. }
  2124. if nr != nw {
  2125. err = io.ErrShortWrite
  2126. break
  2127. }
  2128. }
  2129. if er != nil {
  2130. if er != io.EOF {
  2131. err = er
  2132. }
  2133. break
  2134. }
  2135. }
  2136. return written, err
  2137. }
  2138. var copyBufPool = sync.Pool{
  2139. New: func() any {
  2140. return make([]byte, 4096)
  2141. },
  2142. }
  2143. func writeChunk(w *bufio.Writer, b []byte) error {
  2144. n := len(b)
  2145. if err := writeHexInt(w, n); err != nil {
  2146. return err
  2147. }
  2148. if _, err := w.Write(strCRLF); err != nil {
  2149. return err
  2150. }
  2151. if _, err := w.Write(b); err != nil {
  2152. return err
  2153. }
  2154. // If is end chunk, write CRLF after writing trailer
  2155. if n > 0 {
  2156. if _, err := w.Write(strCRLF); err != nil {
  2157. return err
  2158. }
  2159. }
  2160. return w.Flush()
  2161. }
  2162. // ErrBodyTooLarge is returned if either request or response body exceeds
  2163. // the given limit.
  2164. var ErrBodyTooLarge = errors.New("body size exceeds the given limit")
  2165. func readBody(r *bufio.Reader, contentLength, maxBodySize int, dst []byte) ([]byte, error) {
  2166. if maxBodySize > 0 && contentLength > maxBodySize {
  2167. return dst, ErrBodyTooLarge
  2168. }
  2169. return appendBodyFixedSize(r, dst, contentLength)
  2170. }
  2171. var errChunkedStream = errors.New("chunked stream")
  2172. func readBodyWithStreaming(r *bufio.Reader, contentLength, maxBodySize int, dst []byte) (b []byte, err error) {
  2173. if contentLength == -1 {
  2174. // handled in requestStream.Read()
  2175. return b, errChunkedStream
  2176. }
  2177. dst = dst[:0]
  2178. readN := maxBodySize
  2179. if readN > contentLength {
  2180. readN = contentLength
  2181. }
  2182. if readN > 8*1024 {
  2183. readN = 8 * 1024
  2184. }
  2185. // A fixed-length pre-read function should be used here; otherwise,
  2186. // it may read content beyond the request body into areas outside
  2187. // the br buffer. This could affect the handling of the next request
  2188. // in the br buffer, if there is one. The original two branches can
  2189. // be handled with this single branch. by the way,
  2190. // fix issue: https://github.com/valyala/fasthttp/issues/1816
  2191. b, err = appendBodyFixedSize(r, dst, readN)
  2192. if err != nil {
  2193. return b, err
  2194. }
  2195. if contentLength > maxBodySize {
  2196. return b, ErrBodyTooLarge
  2197. }
  2198. return b, nil
  2199. }
  2200. func readBodyIdentity(r *bufio.Reader, maxBodySize int, dst []byte) ([]byte, error) {
  2201. dst = dst[:cap(dst)]
  2202. if len(dst) == 0 {
  2203. dst = make([]byte, 1024)
  2204. }
  2205. offset := 0
  2206. for {
  2207. nn, err := r.Read(dst[offset:])
  2208. if nn <= 0 {
  2209. switch {
  2210. case errors.Is(err, io.EOF):
  2211. return dst[:offset], nil
  2212. case err != nil:
  2213. return dst[:offset], err
  2214. default:
  2215. return dst[:offset], fmt.Errorf("bufio.Read() returned (%d, nil)", nn)
  2216. }
  2217. }
  2218. offset += nn
  2219. if maxBodySize > 0 && offset > maxBodySize {
  2220. return dst[:offset], ErrBodyTooLarge
  2221. }
  2222. if len(dst) == offset {
  2223. n := roundUpForSliceCap(2 * offset)
  2224. if maxBodySize > 0 && n > maxBodySize {
  2225. n = maxBodySize + 1
  2226. }
  2227. b := make([]byte, n)
  2228. copy(b, dst)
  2229. dst = b
  2230. }
  2231. }
  2232. }
  2233. func appendBodyFixedSize(r *bufio.Reader, dst []byte, n int) ([]byte, error) {
  2234. if n == 0 {
  2235. return dst, nil
  2236. }
  2237. offset := len(dst)
  2238. dstLen := offset + n
  2239. if cap(dst) < dstLen {
  2240. b := make([]byte, roundUpForSliceCap(dstLen))
  2241. copy(b, dst)
  2242. dst = b
  2243. }
  2244. dst = dst[:dstLen]
  2245. for {
  2246. nn, err := r.Read(dst[offset:])
  2247. if nn <= 0 {
  2248. switch {
  2249. case errors.Is(err, io.EOF):
  2250. return dst[:offset], io.ErrUnexpectedEOF
  2251. case err != nil:
  2252. return dst[:offset], err
  2253. default:
  2254. return dst[:offset], fmt.Errorf("bufio.Read() returned (%d, nil)", nn)
  2255. }
  2256. }
  2257. offset += nn
  2258. if offset == dstLen {
  2259. return dst, nil
  2260. }
  2261. }
  2262. }
  2263. // ErrBrokenChunk is returned when server receives a broken chunked body (Transfer-Encoding: chunked).
  2264. type ErrBrokenChunk struct {
  2265. error
  2266. }
  2267. func readBodyChunked(r *bufio.Reader, maxBodySize int, dst []byte) ([]byte, error) {
  2268. if len(dst) > 0 {
  2269. // data integrity might be in danger. No idea what we received,
  2270. // but nothing we should write to.
  2271. panic("BUG: expected zero-length buffer")
  2272. }
  2273. strCRLFLen := len(strCRLF)
  2274. for {
  2275. chunkSize, err := parseChunkSize(r)
  2276. if err != nil {
  2277. return dst, err
  2278. }
  2279. if chunkSize == 0 {
  2280. return dst, err
  2281. }
  2282. if maxBodySize > 0 && len(dst)+chunkSize > maxBodySize {
  2283. return dst, ErrBodyTooLarge
  2284. }
  2285. dst, err = appendBodyFixedSize(r, dst, chunkSize+strCRLFLen)
  2286. if err != nil {
  2287. return dst, err
  2288. }
  2289. if !bytes.Equal(dst[len(dst)-strCRLFLen:], strCRLF) {
  2290. return dst, ErrBrokenChunk{
  2291. error: errors.New("cannot find crlf at the end of chunk"),
  2292. }
  2293. }
  2294. dst = dst[:len(dst)-strCRLFLen]
  2295. }
  2296. }
  2297. func parseChunkSize(r *bufio.Reader) (int, error) {
  2298. n, err := readHexInt(r)
  2299. if err != nil {
  2300. return -1, err
  2301. }
  2302. for {
  2303. c, err := r.ReadByte()
  2304. if err != nil {
  2305. return -1, ErrBrokenChunk{
  2306. error: fmt.Errorf("cannot read '\\r' char at the end of chunk size: %w", err),
  2307. }
  2308. }
  2309. // Skip chunk extension after chunk size.
  2310. // Add support later if anyone needs it.
  2311. if c != '\r' {
  2312. // Security: Don't allow newlines in chunk extensions.
  2313. // This can lead to request smuggling issues with some reverse proxies.
  2314. if c == '\n' {
  2315. return -1, ErrBrokenChunk{
  2316. error: errors.New("invalid character '\\n' after chunk size"),
  2317. }
  2318. }
  2319. continue
  2320. }
  2321. if err := r.UnreadByte(); err != nil {
  2322. return -1, ErrBrokenChunk{
  2323. error: fmt.Errorf("cannot unread '\\r' char at the end of chunk size: %w", err),
  2324. }
  2325. }
  2326. break
  2327. }
  2328. err = readCrLf(r)
  2329. if err != nil {
  2330. return -1, err
  2331. }
  2332. return n, nil
  2333. }
  2334. func readCrLf(r *bufio.Reader) error {
  2335. for _, exp := range []byte{'\r', '\n'} {
  2336. c, err := r.ReadByte()
  2337. if err != nil {
  2338. return ErrBrokenChunk{
  2339. error: fmt.Errorf("cannot read %q char at the end of chunk size: %w", exp, err),
  2340. }
  2341. }
  2342. if c != exp {
  2343. return ErrBrokenChunk{
  2344. error: fmt.Errorf("unexpected char %q at the end of chunk size. Expected %q", c, exp),
  2345. }
  2346. }
  2347. }
  2348. return nil
  2349. }
  2350. // SetTimeout sets timeout for the request.
  2351. //
  2352. // The following code:
  2353. //
  2354. // req.SetTimeout(t)
  2355. // c.Do(&req, &resp)
  2356. //
  2357. // is equivalent to
  2358. //
  2359. // c.DoTimeout(&req, &resp, t)
  2360. func (req *Request) SetTimeout(t time.Duration) {
  2361. req.timeout = t
  2362. }