http.go 70 KB

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