http.go 66 KB

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