http.go 69 KB

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