http.go 60 KB

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