http.go 63 KB

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