http.go 60 KB

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