header.go 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383
  1. package fasthttp
  2. import (
  3. "bufio"
  4. "bytes"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "iter"
  9. "sync"
  10. "sync/atomic"
  11. "time"
  12. )
  13. const (
  14. rChar = byte('\r')
  15. nChar = byte('\n')
  16. )
  17. type header struct {
  18. h []argsKV
  19. cookies []argsKV
  20. bufK []byte
  21. bufV []byte
  22. contentLengthBytes []byte
  23. contentType []byte
  24. protocol []byte
  25. mulHeader [][]byte
  26. trailer [][]byte
  27. contentLength int
  28. disableNormalizing bool
  29. secureErrorLogMessage bool
  30. noHTTP11 bool
  31. connectionClose bool
  32. noDefaultContentType bool
  33. }
  34. // ResponseHeader represents HTTP response header.
  35. //
  36. // It is forbidden copying ResponseHeader instances.
  37. // Create new instances instead and use CopyTo.
  38. //
  39. // ResponseHeader instance MUST NOT be used from concurrently running
  40. // goroutines.
  41. type ResponseHeader struct {
  42. noCopy noCopy
  43. header
  44. statusMessage []byte
  45. contentEncoding []byte
  46. server []byte
  47. statusCode int
  48. noDefaultDate bool
  49. }
  50. // RequestHeader represents HTTP request header.
  51. //
  52. // It is forbidden copying RequestHeader instances.
  53. // Create new instances instead and use CopyTo.
  54. //
  55. // RequestHeader instance MUST NOT be used from concurrently running
  56. // goroutines.
  57. type RequestHeader struct {
  58. noCopy noCopy
  59. header
  60. method []byte
  61. requestURI []byte
  62. host []byte
  63. userAgent []byte
  64. // stores an immutable copy of headers as they were received from the
  65. // wire.
  66. rawHeaders []byte
  67. disableSpecialHeader bool
  68. cookiesCollected bool
  69. }
  70. // SetContentRange sets 'Content-Range: bytes startPos-endPos/contentLength'
  71. // header.
  72. func (h *ResponseHeader) SetContentRange(startPos, endPos, contentLength int) {
  73. b := h.bufV[:0]
  74. b = append(b, strBytes...)
  75. b = append(b, ' ')
  76. b = AppendUint(b, startPos)
  77. b = append(b, '-')
  78. b = AppendUint(b, endPos)
  79. b = append(b, '/')
  80. b = AppendUint(b, contentLength)
  81. h.bufV = b
  82. h.setNonSpecial(strContentRange, h.bufV)
  83. }
  84. // SetByteRange sets 'Range: bytes=startPos-endPos' header.
  85. //
  86. // - If startPos is negative, then 'bytes=-startPos' value is set.
  87. // - If endPos is negative, then 'bytes=startPos-' value is set.
  88. func (h *RequestHeader) SetByteRange(startPos, endPos int) {
  89. b := h.bufV[:0]
  90. b = append(b, strBytes...)
  91. b = append(b, '=')
  92. if startPos >= 0 {
  93. b = AppendUint(b, startPos)
  94. } else {
  95. endPos = -startPos
  96. }
  97. b = append(b, '-')
  98. if endPos >= 0 {
  99. b = AppendUint(b, endPos)
  100. }
  101. h.bufV = b
  102. h.setNonSpecial(strRange, h.bufV)
  103. }
  104. // StatusCode returns response status code.
  105. func (h *ResponseHeader) StatusCode() int {
  106. if h.statusCode == 0 {
  107. return StatusOK
  108. }
  109. return h.statusCode
  110. }
  111. // SetStatusCode sets response status code.
  112. func (h *ResponseHeader) SetStatusCode(statusCode int) {
  113. h.statusCode = statusCode
  114. }
  115. // StatusMessage returns response status message.
  116. func (h *ResponseHeader) StatusMessage() []byte {
  117. return h.statusMessage
  118. }
  119. // SetStatusMessage sets response status message bytes.
  120. func (h *ResponseHeader) SetStatusMessage(statusMessage []byte) {
  121. h.statusMessage = append(h.statusMessage[:0], statusMessage...)
  122. }
  123. // SetProtocol sets response protocol bytes.
  124. func (h *ResponseHeader) SetProtocol(protocol []byte) {
  125. h.protocol = append(h.protocol[:0], protocol...)
  126. }
  127. // SetLastModified sets 'Last-Modified' header to the given value.
  128. func (h *ResponseHeader) SetLastModified(t time.Time) {
  129. h.bufV = AppendHTTPDate(h.bufV[:0], t)
  130. h.setNonSpecial(strLastModified, h.bufV)
  131. }
  132. // ConnectionClose returns true if 'Connection: close' header is set.
  133. func (h *header) ConnectionClose() bool {
  134. return h.connectionClose
  135. }
  136. // SetConnectionClose sets 'Connection: close' header.
  137. func (h *header) SetConnectionClose() {
  138. h.connectionClose = true
  139. }
  140. // ResetConnectionClose clears 'Connection: close' header if it exists.
  141. func (h *header) ResetConnectionClose() {
  142. if h.connectionClose {
  143. h.connectionClose = false
  144. h.h = delAllArgs(h.h, HeaderConnection)
  145. }
  146. }
  147. // ConnectionUpgrade returns true if 'Connection: Upgrade' header is set.
  148. func (h *ResponseHeader) ConnectionUpgrade() bool {
  149. return hasHeaderValue(h.Peek(HeaderConnection), strUpgrade)
  150. }
  151. // ConnectionUpgrade returns true if 'Connection: Upgrade' header is set.
  152. func (h *RequestHeader) ConnectionUpgrade() bool {
  153. return hasHeaderValue(h.Peek(HeaderConnection), strUpgrade)
  154. }
  155. // PeekCookie is able to returns cookie by a given key from response.
  156. func (h *ResponseHeader) PeekCookie(key string) []byte {
  157. return peekArgStr(h.cookies, key)
  158. }
  159. // ContentLength returns Content-Length header value.
  160. //
  161. // It may be negative:
  162. // -1 means Transfer-Encoding: chunked.
  163. // -2 means Transfer-Encoding: identity.
  164. func (h *ResponseHeader) ContentLength() int {
  165. return h.contentLength
  166. }
  167. // ContentLength returns Content-Length header value.
  168. //
  169. // It may be negative:
  170. // -1 means Transfer-Encoding: chunked.
  171. // -2 means Transfer-Encoding: identity.
  172. func (h *RequestHeader) ContentLength() int {
  173. if h.disableSpecialHeader {
  174. // Parse Content-Length from raw headers when special headers are disabled
  175. v := peekArgBytes(h.h, strContentLength)
  176. if len(v) == 0 {
  177. // Check for Transfer-Encoding: chunked
  178. te := peekArgBytes(h.h, strTransferEncoding)
  179. if bytes.Equal(te, strChunked) {
  180. return -1 // chunked
  181. }
  182. return -2 // identity
  183. }
  184. n, err := parseContentLength(v)
  185. if err != nil {
  186. return -2 // identity on parse error
  187. }
  188. return n
  189. }
  190. return h.contentLength
  191. }
  192. // SetContentLength sets Content-Length header value.
  193. //
  194. // Content-Length may be negative:
  195. // -1 means Transfer-Encoding: chunked.
  196. // -2 means Transfer-Encoding: identity.
  197. func (h *ResponseHeader) SetContentLength(contentLength int) {
  198. if h.mustSkipContentLength() {
  199. return
  200. }
  201. h.contentLength = contentLength
  202. if contentLength >= 0 {
  203. h.contentLengthBytes = AppendUint(h.contentLengthBytes[:0], contentLength)
  204. h.h = delAllArgs(h.h, HeaderTransferEncoding)
  205. return
  206. } else if contentLength == -1 {
  207. h.contentLengthBytes = h.contentLengthBytes[:0]
  208. h.h = setArgBytes(h.h, strTransferEncoding, strChunked, argsHasValue)
  209. return
  210. }
  211. h.SetConnectionClose()
  212. }
  213. func (h *ResponseHeader) mustSkipContentLength() bool {
  214. // From http/1.1 specs:
  215. // All 1xx (informational), 204 (no content), and 304 (not modified) responses MUST NOT include a message-body
  216. statusCode := h.StatusCode()
  217. // Fast path.
  218. if statusCode < 100 || statusCode == StatusOK {
  219. return false
  220. }
  221. // Slow path.
  222. return statusCode == StatusNotModified || statusCode == StatusNoContent || statusCode < 200
  223. }
  224. // SetContentLength sets Content-Length header value.
  225. //
  226. // Negative content-length sets 'Transfer-Encoding: chunked' header.
  227. func (h *RequestHeader) SetContentLength(contentLength int) {
  228. h.contentLength = contentLength
  229. if contentLength >= 0 {
  230. h.contentLengthBytes = AppendUint(h.contentLengthBytes[:0], contentLength)
  231. h.h = delAllArgs(h.h, HeaderTransferEncoding)
  232. } else {
  233. h.contentLengthBytes = h.contentLengthBytes[:0]
  234. h.h = setArgBytes(h.h, strTransferEncoding, strChunked, argsHasValue)
  235. }
  236. }
  237. func (h *ResponseHeader) isCompressibleContentType() bool {
  238. contentType := h.ContentType()
  239. return bytes.HasPrefix(contentType, strTextSlash) ||
  240. bytes.HasPrefix(contentType, strApplicationSlash) ||
  241. bytes.HasPrefix(contentType, strImageSVG) ||
  242. bytes.HasPrefix(contentType, strImageIcon) ||
  243. bytes.HasPrefix(contentType, strFontSlash) ||
  244. bytes.HasPrefix(contentType, strMultipartSlash)
  245. }
  246. // ContentType returns Content-Type header value.
  247. func (h *ResponseHeader) ContentType() []byte {
  248. contentType := h.contentType
  249. if !h.noDefaultContentType && len(h.contentType) == 0 {
  250. contentType = defaultContentType
  251. }
  252. return contentType
  253. }
  254. // SetContentType sets Content-Type header value.
  255. func (h *header) SetContentType(contentType string) {
  256. h.contentType = append(h.contentType[:0], contentType...)
  257. }
  258. // SetContentTypeBytes sets Content-Type header value.
  259. func (h *header) SetContentTypeBytes(contentType []byte) {
  260. h.contentType = append(h.contentType[:0], contentType...)
  261. }
  262. // ContentEncoding returns Content-Encoding header value.
  263. func (h *ResponseHeader) ContentEncoding() []byte {
  264. return h.contentEncoding
  265. }
  266. // SetContentEncoding sets Content-Encoding header value.
  267. func (h *ResponseHeader) SetContentEncoding(contentEncoding string) {
  268. h.contentEncoding = append(h.contentEncoding[:0], contentEncoding...)
  269. }
  270. // SetContentEncodingBytes sets Content-Encoding header value.
  271. func (h *ResponseHeader) SetContentEncodingBytes(contentEncoding []byte) {
  272. h.contentEncoding = append(h.contentEncoding[:0], contentEncoding...)
  273. }
  274. // addVaryBytes add value to the 'Vary' header if it's not included.
  275. func (h *ResponseHeader) addVaryBytes(value []byte) {
  276. v := h.peek(strVary)
  277. if len(v) == 0 {
  278. // 'Vary' is not set
  279. h.SetBytesV(HeaderVary, value)
  280. } else if !bytes.Contains(v, value) {
  281. // 'Vary' is set and not contains target value
  282. h.SetBytesV(HeaderVary, append(append(v, ','), value...))
  283. } // else: 'Vary' is set and contains target value
  284. }
  285. // Server returns Server header value.
  286. func (h *ResponseHeader) Server() []byte {
  287. return h.server
  288. }
  289. // SetServer sets Server header value.
  290. func (h *ResponseHeader) SetServer(server string) {
  291. h.server = append(h.server[:0], server...)
  292. }
  293. // SetServerBytes sets Server header value.
  294. func (h *ResponseHeader) SetServerBytes(server []byte) {
  295. h.server = append(h.server[:0], server...)
  296. }
  297. // ContentType returns Content-Type header value.
  298. func (h *RequestHeader) ContentType() []byte {
  299. if h.disableSpecialHeader {
  300. return peekArgBytes(h.h, []byte(HeaderContentType))
  301. }
  302. return h.contentType
  303. }
  304. // ContentEncoding returns Content-Encoding header value.
  305. func (h *RequestHeader) ContentEncoding() []byte {
  306. return peekArgBytes(h.h, strContentEncoding)
  307. }
  308. // SetContentEncoding sets Content-Encoding header value.
  309. func (h *RequestHeader) SetContentEncoding(contentEncoding string) {
  310. h.SetBytesK(strContentEncoding, contentEncoding)
  311. }
  312. // SetContentEncodingBytes sets Content-Encoding header value.
  313. func (h *RequestHeader) SetContentEncodingBytes(contentEncoding []byte) {
  314. h.setNonSpecial(strContentEncoding, contentEncoding)
  315. }
  316. // SetMultipartFormBoundary sets the following Content-Type:
  317. // 'multipart/form-data; boundary=...'
  318. // where ... is substituted by the given boundary.
  319. func (h *RequestHeader) SetMultipartFormBoundary(boundary string) {
  320. b := h.bufV[:0]
  321. b = append(b, strMultipartFormData...)
  322. b = append(b, ';', ' ')
  323. b = append(b, strBoundary...)
  324. b = append(b, '=')
  325. b = append(b, boundary...)
  326. h.bufV = b
  327. h.SetContentTypeBytes(h.bufV)
  328. }
  329. // SetMultipartFormBoundaryBytes sets the following Content-Type:
  330. // 'multipart/form-data; boundary=...'
  331. // where ... is substituted by the given boundary.
  332. func (h *RequestHeader) SetMultipartFormBoundaryBytes(boundary []byte) {
  333. b := h.bufV[:0]
  334. b = append(b, strMultipartFormData...)
  335. b = append(b, ';', ' ')
  336. b = append(b, strBoundary...)
  337. b = append(b, '=')
  338. b = append(b, boundary...)
  339. h.bufV = b
  340. h.SetContentTypeBytes(h.bufV)
  341. }
  342. // SetTrailer sets header Trailer value for chunked response
  343. // to indicate which headers will be sent after the body.
  344. //
  345. // Use Set to set the trailer header later.
  346. //
  347. // Trailers are only supported with chunked transfer.
  348. // Trailers allow the sender to include additional headers at the end of chunked messages.
  349. //
  350. // The following trailers are forbidden:
  351. // 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length),
  352. // 2. routing (e.g., Host),
  353. // 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]),
  354. // 4. authentication (e.g., see [RFC7235] and [RFC6265]),
  355. // 5. response control data (e.g., see Section 7.1 of [RFC7231]),
  356. // 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer)
  357. //
  358. // Return ErrBadTrailer if contain any forbidden trailers.
  359. func (h *header) SetTrailer(trailer string) error {
  360. return h.SetTrailerBytes(s2b(trailer))
  361. }
  362. // SetTrailerBytes sets Trailer header value for chunked response
  363. // to indicate which headers will be sent after the body.
  364. //
  365. // Use Set to set the trailer header later.
  366. //
  367. // Trailers are only supported with chunked transfer.
  368. // Trailers allow the sender to include additional headers at the end of chunked messages.
  369. //
  370. // The following trailers are forbidden:
  371. // 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length),
  372. // 2. routing (e.g., Host),
  373. // 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]),
  374. // 4. authentication (e.g., see [RFC7235] and [RFC6265]),
  375. // 5. response control data (e.g., see Section 7.1 of [RFC7231]),
  376. // 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer)
  377. //
  378. // Return ErrBadTrailer if contain any forbidden trailers.
  379. func (h *header) SetTrailerBytes(trailer []byte) error {
  380. h.trailer = h.trailer[:0]
  381. return h.AddTrailerBytes(trailer)
  382. }
  383. // AddTrailer add Trailer header value for chunked response
  384. // to indicate which headers will be sent after the body.
  385. //
  386. // Use Set to set the trailer header later.
  387. //
  388. // Trailers are only supported with chunked transfer.
  389. // Trailers allow the sender to include additional headers at the end of chunked messages.
  390. //
  391. // The following trailers are forbidden:
  392. // 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length),
  393. // 2. routing (e.g., Host),
  394. // 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]),
  395. // 4. authentication (e.g., see [RFC7235] and [RFC6265]),
  396. // 5. response control data (e.g., see Section 7.1 of [RFC7231]),
  397. // 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer)
  398. //
  399. // Return ErrBadTrailer if contain any forbidden trailers.
  400. func (h *header) AddTrailer(trailer string) error {
  401. return h.AddTrailerBytes(s2b(trailer))
  402. }
  403. var ErrBadTrailer = errors.New("contain forbidden trailer")
  404. // AddTrailerBytes add Trailer header value for chunked response
  405. // to indicate which headers will be sent after the body.
  406. //
  407. // Use Set to set the trailer header later.
  408. //
  409. // Trailers are only supported with chunked transfer.
  410. // Trailers allow the sender to include additional headers at the end of chunked messages.
  411. //
  412. // The following trailers are forbidden:
  413. // 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length),
  414. // 2. routing (e.g., Host),
  415. // 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]),
  416. // 4. authentication (e.g., see [RFC7235] and [RFC6265]),
  417. // 5. response control data (e.g., see Section 7.1 of [RFC7231]),
  418. // 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer)
  419. //
  420. // Return ErrBadTrailer if contain any forbidden trailers.
  421. func (h *header) AddTrailerBytes(trailer []byte) (err error) {
  422. for i := -1; i+1 < len(trailer); {
  423. trailer = trailer[i+1:]
  424. i = bytes.IndexByte(trailer, ',')
  425. if i < 0 {
  426. i = len(trailer)
  427. }
  428. key := trailer[:i]
  429. for len(key) > 0 && key[0] == ' ' {
  430. key = key[1:]
  431. }
  432. for len(key) > 0 && key[len(key)-1] == ' ' {
  433. key = key[:len(key)-1]
  434. }
  435. // Forbidden by RFC 7230, section 4.1.2
  436. if isBadTrailer(key) {
  437. err = ErrBadTrailer
  438. continue
  439. }
  440. h.bufK = append(h.bufK[:0], key...)
  441. normalizeHeaderKey(h.bufK, h.disableNormalizing || bytes.IndexByte(h.bufK, ' ') != -1)
  442. if cap(h.trailer) > len(h.trailer) {
  443. h.trailer = h.trailer[:len(h.trailer)+1]
  444. h.trailer[len(h.trailer)-1] = append(h.trailer[len(h.trailer)-1][:0], h.bufK...)
  445. } else {
  446. key = make([]byte, len(h.bufK))
  447. copy(key, h.bufK)
  448. h.trailer = append(h.trailer, key)
  449. }
  450. }
  451. return err
  452. }
  453. // validHeaderFieldByte returns true if c valid header field byte
  454. // as defined by RFC 7230.
  455. func validHeaderFieldByte(c byte) bool {
  456. return c < 128 && validHeaderFieldByteTable[c] == 1
  457. }
  458. // validHeaderValueByte returns true if c valid header value byte
  459. // as defined by RFC 7230.
  460. func validHeaderValueByte(c byte) bool {
  461. return validHeaderValueByteTable[c] == 1
  462. }
  463. // isValidHeaderKey returns true if a is a valid header key.
  464. func isValidHeaderKey(a []byte) bool {
  465. if len(a) == 0 {
  466. return false
  467. }
  468. // See if a looks like a header key. If not, return it unchanged.
  469. noCanon := false
  470. for _, c := range a {
  471. if validHeaderFieldByte(c) {
  472. continue
  473. }
  474. // Don't canonicalize.
  475. if c == ' ' {
  476. // We accept invalid headers with a space before the
  477. // colon, but must not canonicalize them.
  478. // See https://go.dev/issue/34540.
  479. noCanon = true
  480. continue
  481. }
  482. return false
  483. }
  484. if noCanon {
  485. return true
  486. }
  487. return true
  488. }
  489. // VisitHeaderParams calls f for each parameter in the given header bytes.
  490. // It stops processing when f returns false or an invalid parameter is found.
  491. // Parameter values may be quoted, in which case \ is treated as an escape
  492. // character, and the value is unquoted before being passed to value.
  493. // See: https://www.rfc-editor.org/rfc/rfc9110#section-5.6.6
  494. //
  495. // f must not retain references to key and/or value after returning.
  496. // Copy key and/or value contents before returning if you need retaining them.
  497. func VisitHeaderParams(b []byte, f func(key, value []byte) bool) {
  498. for len(b) > 0 {
  499. idxSemi := 0
  500. for idxSemi < len(b) && b[idxSemi] != ';' {
  501. idxSemi++
  502. }
  503. if idxSemi >= len(b) {
  504. return
  505. }
  506. b = b[idxSemi+1:]
  507. for len(b) > 0 && b[0] == ' ' {
  508. b = b[1:]
  509. }
  510. n := 0
  511. if len(b) == 0 || !validHeaderFieldByte(b[n]) {
  512. return
  513. }
  514. n++
  515. for n < len(b) && validHeaderFieldByte(b[n]) {
  516. n++
  517. }
  518. if n >= len(b)-1 || b[n] != '=' {
  519. return
  520. }
  521. param := b[:n]
  522. n++
  523. switch {
  524. case validHeaderFieldByte(b[n]):
  525. m := n
  526. n++
  527. for n < len(b) && validHeaderFieldByte(b[n]) {
  528. n++
  529. }
  530. if !f(param, b[m:n]) {
  531. return
  532. }
  533. case b[n] == '"':
  534. foundEndQuote := false
  535. escaping := false
  536. n++
  537. m := n
  538. for ; n < len(b); n++ {
  539. if b[n] == '"' && !escaping {
  540. foundEndQuote = true
  541. break
  542. }
  543. escaping = (b[n] == '\\' && !escaping)
  544. }
  545. if !foundEndQuote {
  546. return
  547. }
  548. if !f(param, b[m:n]) {
  549. return
  550. }
  551. n++
  552. default:
  553. return
  554. }
  555. b = b[n:]
  556. }
  557. }
  558. // MultipartFormBoundary returns boundary part
  559. // from 'multipart/form-data; boundary=...' Content-Type.
  560. func (h *RequestHeader) MultipartFormBoundary() []byte {
  561. b := h.ContentType()
  562. if !bytes.HasPrefix(b, strMultipartFormData) {
  563. return nil
  564. }
  565. b = b[len(strMultipartFormData):]
  566. if len(b) == 0 || b[0] != ';' {
  567. return nil
  568. }
  569. var n int
  570. for len(b) > 0 {
  571. n++
  572. for len(b) > n && b[n] == ' ' {
  573. n++
  574. }
  575. b = b[n:]
  576. if !bytes.HasPrefix(b, strBoundary) {
  577. if n = bytes.IndexByte(b, ';'); n < 0 {
  578. return nil
  579. }
  580. continue
  581. }
  582. b = b[len(strBoundary):]
  583. if len(b) == 0 || b[0] != '=' {
  584. return nil
  585. }
  586. b = b[1:]
  587. if n = bytes.IndexByte(b, ';'); n >= 0 {
  588. b = b[:n]
  589. }
  590. if len(b) > 1 && b[0] == '"' && b[len(b)-1] == '"' {
  591. b = b[1 : len(b)-1]
  592. }
  593. return b
  594. }
  595. return nil
  596. }
  597. // Host returns Host header value.
  598. func (h *RequestHeader) Host() []byte {
  599. if h.disableSpecialHeader {
  600. return peekArgBytes(h.h, []byte(HeaderHost))
  601. }
  602. return h.host
  603. }
  604. // SetHost sets Host header value.
  605. func (h *RequestHeader) SetHost(host string) {
  606. h.host = append(h.host[:0], host...)
  607. }
  608. // SetHostBytes sets Host header value.
  609. func (h *RequestHeader) SetHostBytes(host []byte) {
  610. h.host = append(h.host[:0], host...)
  611. }
  612. // UserAgent returns User-Agent header value.
  613. func (h *RequestHeader) UserAgent() []byte {
  614. if h.disableSpecialHeader {
  615. return peekArgBytes(h.h, []byte(HeaderUserAgent))
  616. }
  617. return h.userAgent
  618. }
  619. // SetUserAgent sets User-Agent header value.
  620. func (h *RequestHeader) SetUserAgent(userAgent string) {
  621. h.userAgent = append(h.userAgent[:0], userAgent...)
  622. }
  623. // SetUserAgentBytes sets User-Agent header value.
  624. func (h *RequestHeader) SetUserAgentBytes(userAgent []byte) {
  625. h.userAgent = append(h.userAgent[:0], userAgent...)
  626. }
  627. // Referer returns Referer header value.
  628. func (h *RequestHeader) Referer() []byte {
  629. return peekArgBytes(h.h, strReferer)
  630. }
  631. // SetReferer sets Referer header value.
  632. func (h *RequestHeader) SetReferer(referer string) {
  633. h.SetBytesK(strReferer, referer)
  634. }
  635. // SetRefererBytes sets Referer header value.
  636. func (h *RequestHeader) SetRefererBytes(referer []byte) {
  637. h.setNonSpecial(strReferer, referer)
  638. }
  639. // Method returns HTTP request method.
  640. func (h *RequestHeader) Method() []byte {
  641. if len(h.method) == 0 {
  642. return []byte(MethodGet)
  643. }
  644. return h.method
  645. }
  646. // SetMethod sets HTTP request method.
  647. func (h *RequestHeader) SetMethod(method string) {
  648. h.method = append(h.method[:0], method...)
  649. }
  650. // SetMethodBytes sets HTTP request method.
  651. func (h *RequestHeader) SetMethodBytes(method []byte) {
  652. h.method = append(h.method[:0], method...)
  653. }
  654. // Protocol returns HTTP protocol.
  655. func (h *header) Protocol() []byte {
  656. if len(h.protocol) == 0 {
  657. return strHTTP11
  658. }
  659. return h.protocol
  660. }
  661. // SetProtocol sets HTTP request protocol.
  662. func (h *RequestHeader) SetProtocol(protocol string) {
  663. h.protocol = append(h.protocol[:0], protocol...)
  664. h.noHTTP11 = !bytes.Equal(h.protocol, strHTTP11)
  665. }
  666. // SetProtocolBytes sets HTTP request protocol.
  667. func (h *RequestHeader) SetProtocolBytes(protocol []byte) {
  668. h.protocol = append(h.protocol[:0], protocol...)
  669. h.noHTTP11 = !bytes.Equal(h.protocol, strHTTP11)
  670. }
  671. // RequestURI returns RequestURI from the first HTTP request line.
  672. func (h *RequestHeader) RequestURI() []byte {
  673. requestURI := h.requestURI
  674. if len(requestURI) == 0 {
  675. requestURI = strSlash
  676. }
  677. return requestURI
  678. }
  679. // SetRequestURI sets RequestURI for the first HTTP request line.
  680. // RequestURI must be properly encoded.
  681. // Use URI.RequestURI for constructing proper RequestURI if unsure.
  682. func (h *RequestHeader) SetRequestURI(requestURI string) {
  683. h.requestURI = append(h.requestURI[:0], requestURI...)
  684. }
  685. // SetRequestURIBytes sets RequestURI for the first HTTP request line.
  686. // RequestURI must be properly encoded.
  687. // Use URI.RequestURI for constructing proper RequestURI if unsure.
  688. func (h *RequestHeader) SetRequestURIBytes(requestURI []byte) {
  689. h.requestURI = append(h.requestURI[:0], requestURI...)
  690. }
  691. // IsGet returns true if request method is GET.
  692. func (h *RequestHeader) IsGet() bool {
  693. return string(h.Method()) == MethodGet
  694. }
  695. // IsPost returns true if request method is POST.
  696. func (h *RequestHeader) IsPost() bool {
  697. return string(h.Method()) == MethodPost
  698. }
  699. // IsPut returns true if request method is PUT.
  700. func (h *RequestHeader) IsPut() bool {
  701. return string(h.Method()) == MethodPut
  702. }
  703. // IsHead returns true if request method is HEAD.
  704. func (h *RequestHeader) IsHead() bool {
  705. return string(h.Method()) == MethodHead
  706. }
  707. // IsDelete returns true if request method is DELETE.
  708. func (h *RequestHeader) IsDelete() bool {
  709. return string(h.Method()) == MethodDelete
  710. }
  711. // IsConnect returns true if request method is CONNECT.
  712. func (h *RequestHeader) IsConnect() bool {
  713. return string(h.Method()) == MethodConnect
  714. }
  715. // IsOptions returns true if request method is OPTIONS.
  716. func (h *RequestHeader) IsOptions() bool {
  717. return string(h.Method()) == MethodOptions
  718. }
  719. // IsTrace returns true if request method is TRACE.
  720. func (h *RequestHeader) IsTrace() bool {
  721. return string(h.Method()) == MethodTrace
  722. }
  723. // IsPatch returns true if request method is PATCH.
  724. func (h *RequestHeader) IsPatch() bool {
  725. return string(h.Method()) == MethodPatch
  726. }
  727. // IsHTTP11 returns true if the header is HTTP/1.1.
  728. func (h *header) IsHTTP11() bool {
  729. return !h.noHTTP11
  730. }
  731. // HasAcceptEncoding returns true if the header contains
  732. // the given Accept-Encoding value.
  733. func (h *RequestHeader) HasAcceptEncoding(acceptEncoding string) bool {
  734. h.bufV = append(h.bufV[:0], acceptEncoding...)
  735. return h.HasAcceptEncodingBytes(h.bufV)
  736. }
  737. // HasAcceptEncodingBytes returns true if the header contains
  738. // the given Accept-Encoding value.
  739. func (h *RequestHeader) HasAcceptEncodingBytes(acceptEncoding []byte) bool {
  740. ae := h.peek(strAcceptEncoding)
  741. n := bytes.Index(ae, acceptEncoding)
  742. if n < 0 {
  743. return false
  744. }
  745. b := ae[n+len(acceptEncoding):]
  746. if len(b) > 0 && b[0] != ',' {
  747. return false
  748. }
  749. if n == 0 {
  750. return true
  751. }
  752. return ae[n-1] == ' '
  753. }
  754. // Len returns the number of headers set,
  755. // i.e. the number of times f is called in VisitAll.
  756. func (h *ResponseHeader) Len() int {
  757. n := 0
  758. for range h.All() {
  759. n++
  760. }
  761. return n
  762. }
  763. // Len returns the number of headers set,
  764. // i.e. the number of times f is called in VisitAll.
  765. func (h *RequestHeader) Len() int {
  766. n := 0
  767. for range h.All() {
  768. n++
  769. }
  770. return n
  771. }
  772. // DisableSpecialHeader disables special header processing.
  773. // fasthttp will not set any special headers for you, such as Host, Content-Type, User-Agent, etc.
  774. // You must set everything yourself.
  775. // If RequestHeader.Read() is called, special headers will be ignored.
  776. // This can be used to control case and order of special headers.
  777. // This is generally not recommended.
  778. func (h *RequestHeader) DisableSpecialHeader() {
  779. h.disableSpecialHeader = true
  780. }
  781. // EnableSpecialHeader enables special header processing.
  782. // fasthttp will send Host, Content-Type, User-Agent, etc headers for you.
  783. // This is suggested and enabled by default.
  784. func (h *RequestHeader) EnableSpecialHeader() {
  785. h.disableSpecialHeader = false
  786. }
  787. // DisableNormalizing disables header names' normalization.
  788. //
  789. // By default all the header names are normalized by uppercasing
  790. // the first letter and all the first letters following dashes,
  791. // while lowercasing all the other letters.
  792. // Examples:
  793. //
  794. // - CONNECTION -> Connection
  795. // - conteNT-tYPE -> Content-Type
  796. // - foo-bar-baz -> Foo-Bar-Baz
  797. //
  798. // Disable header names' normalization only if know what are you doing.
  799. func (h *header) DisableNormalizing() {
  800. h.disableNormalizing = true
  801. }
  802. // EnableNormalizing enables header names' normalization.
  803. //
  804. // Header names are normalized by uppercasing the first letter and
  805. // all the first letters following dashes, while lowercasing all
  806. // the other letters.
  807. // Examples:
  808. //
  809. // - CONNECTION -> Connection
  810. // - conteNT-tYPE -> Content-Type
  811. // - foo-bar-baz -> Foo-Bar-Baz
  812. //
  813. // This is enabled by default unless disabled using DisableNormalizing().
  814. func (h *header) EnableNormalizing() {
  815. h.disableNormalizing = false
  816. }
  817. // SetNoDefaultContentType allows you to control if a default Content-Type header will be set (false) or not (true).
  818. func (h *header) SetNoDefaultContentType(noDefaultContentType bool) {
  819. h.noDefaultContentType = noDefaultContentType
  820. }
  821. // Reset clears response header.
  822. func (h *ResponseHeader) Reset() {
  823. h.disableNormalizing = false
  824. h.SetNoDefaultContentType(false)
  825. h.noDefaultDate = false
  826. h.resetSkipNormalize()
  827. }
  828. func (h *ResponseHeader) resetSkipNormalize() {
  829. h.noHTTP11 = false
  830. h.connectionClose = false
  831. h.statusCode = 0
  832. h.statusMessage = h.statusMessage[:0]
  833. h.protocol = h.protocol[:0]
  834. h.contentLength = 0
  835. h.contentLengthBytes = h.contentLengthBytes[:0]
  836. h.contentType = h.contentType[:0]
  837. h.contentEncoding = h.contentEncoding[:0]
  838. h.server = h.server[:0]
  839. h.h = h.h[:0]
  840. h.cookies = h.cookies[:0]
  841. h.trailer = h.trailer[:0]
  842. h.mulHeader = h.mulHeader[:0]
  843. }
  844. // Reset clears request header.
  845. func (h *RequestHeader) Reset() {
  846. h.disableSpecialHeader = false
  847. h.disableNormalizing = false
  848. h.SetNoDefaultContentType(false)
  849. h.resetSkipNormalize()
  850. }
  851. func (h *RequestHeader) resetSkipNormalize() {
  852. h.noHTTP11 = false
  853. h.connectionClose = false
  854. h.contentLength = 0
  855. h.contentLengthBytes = h.contentLengthBytes[:0]
  856. h.method = h.method[:0]
  857. h.protocol = h.protocol[:0]
  858. h.requestURI = h.requestURI[:0]
  859. h.host = h.host[:0]
  860. h.contentType = h.contentType[:0]
  861. h.userAgent = h.userAgent[:0]
  862. h.trailer = h.trailer[:0]
  863. h.mulHeader = h.mulHeader[:0]
  864. h.h = h.h[:0]
  865. h.cookies = h.cookies[:0]
  866. h.cookiesCollected = false
  867. h.rawHeaders = h.rawHeaders[:0]
  868. }
  869. func (h *header) copyTo(dst *header) {
  870. dst.disableNormalizing = h.disableNormalizing
  871. dst.noHTTP11 = h.noHTTP11
  872. dst.connectionClose = h.connectionClose
  873. dst.noDefaultContentType = h.noDefaultContentType
  874. dst.contentLength = h.contentLength
  875. dst.contentLengthBytes = append(dst.contentLengthBytes, h.contentLengthBytes...)
  876. dst.protocol = append(dst.protocol, h.protocol...)
  877. dst.contentType = append(dst.contentType, h.contentType...)
  878. dst.trailer = copyTrailer(dst.trailer, h.trailer)
  879. dst.cookies = copyArgs(dst.cookies, h.cookies)
  880. dst.h = copyArgs(dst.h, h.h)
  881. }
  882. // CopyTo copies all the headers to dst.
  883. func (h *ResponseHeader) CopyTo(dst *ResponseHeader) {
  884. dst.Reset()
  885. h.copyTo(&dst.header)
  886. dst.noDefaultDate = h.noDefaultDate
  887. dst.statusCode = h.statusCode
  888. dst.statusMessage = append(dst.statusMessage, h.statusMessage...)
  889. dst.contentEncoding = append(dst.contentEncoding, h.contentEncoding...)
  890. dst.server = append(dst.server, h.server...)
  891. }
  892. // CopyTo copies all the headers to dst.
  893. func (h *RequestHeader) CopyTo(dst *RequestHeader) {
  894. dst.Reset()
  895. h.copyTo(&dst.header)
  896. dst.method = append(dst.method, h.method...)
  897. dst.requestURI = append(dst.requestURI, h.requestURI...)
  898. dst.host = append(dst.host, h.host...)
  899. dst.userAgent = append(dst.userAgent, h.userAgent...)
  900. dst.cookiesCollected = h.cookiesCollected
  901. dst.rawHeaders = append(dst.rawHeaders, h.rawHeaders...)
  902. }
  903. // All returns an iterator over key-value pairs in h.
  904. //
  905. // The key and value may invalid outside the iteration loop.
  906. // Copy key and/or value contents for each iteration if you need retaining
  907. // them.
  908. func (h *ResponseHeader) All() iter.Seq2[[]byte, []byte] {
  909. return func(yield func([]byte, []byte) bool) {
  910. if len(h.contentLengthBytes) > 0 && !yield(strContentLength, h.contentLengthBytes) {
  911. return
  912. }
  913. if contentType := h.ContentType(); len(contentType) > 0 && !yield(strContentType, contentType) {
  914. return
  915. }
  916. if contentEncoding := h.ContentEncoding(); len(contentEncoding) > 0 && !yield(strContentEncoding, contentEncoding) {
  917. return
  918. }
  919. if server := h.Server(); len(server) > 0 && !yield(strServer, server) {
  920. return
  921. }
  922. for i := range h.cookies {
  923. if !yield(strSetCookie, h.cookies[i].value) {
  924. return
  925. }
  926. }
  927. if len(h.trailer) > 0 && !yield(strTrailer, appendTrailerBytes(nil, h.trailer, strCommaSpace)) {
  928. return
  929. }
  930. for i := range h.h {
  931. if !yield(h.h[i].key, h.h[i].value) {
  932. return
  933. }
  934. }
  935. if h.ConnectionClose() && !yield(strConnection, strClose) {
  936. return
  937. }
  938. }
  939. }
  940. // VisitAll calls f for each header.
  941. //
  942. // f must not retain references to key and/or value after returning.
  943. // Copy key and/or value contents before returning if you need retaining them.
  944. //
  945. // Deprecated: Use All instead.
  946. func (h *ResponseHeader) VisitAll(f func(key, value []byte)) {
  947. h.All()(func(key, value []byte) bool {
  948. f(key, value)
  949. return true
  950. })
  951. }
  952. // Trailers returns an iterator over trailers in h.
  953. //
  954. // The value of trailer may invalid outside the iteration loop.
  955. func (h *header) Trailers() iter.Seq[[]byte] {
  956. return func(yield func([]byte) bool) {
  957. for i := range h.trailer {
  958. if !yield(h.trailer[i]) {
  959. break
  960. }
  961. }
  962. }
  963. }
  964. // VisitAllTrailer calls f for each response Trailer.
  965. //
  966. // f must not retain references to value after returning.
  967. //
  968. // Deprecated: Use Trailers instead.
  969. func (h *header) VisitAllTrailer(f func(value []byte)) {
  970. h.Trailers()(func(v []byte) bool {
  971. f(v)
  972. return true
  973. })
  974. }
  975. // Cookies returns an iterator over key-value paired response cookie in h.
  976. //
  977. // Cookie name is passed in key and the whole Set-Cookie header value
  978. // is passed in value for each iteration. Value may be parsed with
  979. // Cookie.ParseBytes().
  980. //
  981. // The key and value may invalid outside the iteration loop.
  982. // Copy key and/or value contents for each iteration if you need retaining
  983. // them.
  984. func (h *ResponseHeader) Cookies() iter.Seq2[[]byte, []byte] {
  985. return func(yield func([]byte, []byte) bool) {
  986. for i := range h.cookies {
  987. if !yield(h.cookies[i].key, h.cookies[i].value) {
  988. break
  989. }
  990. }
  991. }
  992. }
  993. // VisitAllCookie calls f for each response cookie.
  994. //
  995. // Cookie name is passed in key and the whole Set-Cookie header value
  996. // is passed in value on each f invocation. Value may be parsed
  997. // with Cookie.ParseBytes().
  998. //
  999. // f must not retain references to key and/or value after returning.
  1000. //
  1001. // Deprecated: Use Cookies instead.
  1002. func (h *ResponseHeader) VisitAllCookie(f func(key, value []byte)) {
  1003. h.Cookies()(func(key, value []byte) bool {
  1004. f(key, value)
  1005. return true
  1006. })
  1007. }
  1008. // Cookies returns an iterator over key-value pairs request cookie in h.
  1009. //
  1010. // The key and value may invalid outside the iteration loop.
  1011. // Copy key and/or value contents for each iteration if you need retaining
  1012. // them.
  1013. func (h *RequestHeader) Cookies() iter.Seq2[[]byte, []byte] {
  1014. return func(yield func([]byte, []byte) bool) {
  1015. h.collectCookies()
  1016. for i := range h.cookies {
  1017. if !yield(h.cookies[i].key, h.cookies[i].value) {
  1018. break
  1019. }
  1020. }
  1021. }
  1022. }
  1023. // VisitAllCookie calls f for each request cookie.
  1024. //
  1025. // f must not retain references to key and/or value after returning.
  1026. //
  1027. // Deprecated: Use Cookies instead.
  1028. func (h *RequestHeader) VisitAllCookie(f func(key, value []byte)) {
  1029. h.Cookies()(func(key, value []byte) bool {
  1030. f(key, value)
  1031. return true
  1032. })
  1033. }
  1034. // All returns an iterator over key-value pairs in h.
  1035. //
  1036. // The key and value may invalid outside the iteration loop.
  1037. // Copy key and/or value contents for each iteration if you need retaining
  1038. // them.
  1039. //
  1040. // To get the headers in order they were received use AllInOrder.
  1041. func (h *RequestHeader) All() iter.Seq2[[]byte, []byte] {
  1042. return func(yield func([]byte, []byte) bool) {
  1043. if host := h.Host(); len(host) > 0 && !yield(strHost, host) {
  1044. return
  1045. }
  1046. if len(h.contentLengthBytes) > 0 && !yield(strContentLength, h.contentLengthBytes) {
  1047. return
  1048. }
  1049. if contentType := h.ContentType(); len(contentType) > 0 && !yield(strContentType, contentType) {
  1050. return
  1051. }
  1052. if userAgent := h.UserAgent(); len(userAgent) > 0 && !yield(strUserAgent, userAgent) {
  1053. return
  1054. }
  1055. if len(h.trailer) > 0 && !yield(strTrailer, appendTrailerBytes(nil, h.trailer, strCommaSpace)) {
  1056. return
  1057. }
  1058. h.collectCookies()
  1059. if len(h.cookies) > 0 {
  1060. h.bufV = appendRequestCookieBytes(h.bufV[:0], h.cookies)
  1061. if !yield(strCookie, h.bufV) {
  1062. return
  1063. }
  1064. }
  1065. for i := range h.h {
  1066. if !yield(h.h[i].key, h.h[i].value) {
  1067. return
  1068. }
  1069. }
  1070. if h.ConnectionClose() && !yield(strConnection, strClose) {
  1071. return
  1072. }
  1073. }
  1074. }
  1075. // VisitAll calls f for each header.
  1076. //
  1077. // f must not retain references to key and/or value after returning.
  1078. // Copy key and/or value contents before returning if you need retaining them.
  1079. //
  1080. // To get the headers in order they were received use VisitAllInOrder.
  1081. //
  1082. // Deprecated: Use All instead.
  1083. func (h *RequestHeader) VisitAll(f func(key, value []byte)) {
  1084. h.All()(func(key, value []byte) bool {
  1085. f(key, value)
  1086. return true
  1087. })
  1088. }
  1089. // AllInOrder returns an iterator over key-value pairs in h in the order they
  1090. // were received.
  1091. //
  1092. // The key and value may invalid outside the iteration loop.
  1093. // Copy key and/or value contents for each iteration if you need retaining
  1094. // them.
  1095. //
  1096. // The returned iterator is slightly slower than All because it has to reparse
  1097. // the raw headers to get the order.
  1098. func (h *RequestHeader) AllInOrder() iter.Seq2[[]byte, []byte] {
  1099. return func(yield func([]byte, []byte) bool) {
  1100. var s headerScanner
  1101. s.b = h.rawHeaders
  1102. for s.next() {
  1103. normalizeHeaderKey(s.key, h.disableNormalizing || bytes.IndexByte(s.key, ' ') != -1)
  1104. if len(s.key) > 0 {
  1105. if !yield(s.key, s.value) {
  1106. break
  1107. }
  1108. }
  1109. }
  1110. }
  1111. }
  1112. // VisitAllInOrder calls f for each header in the order they were received.
  1113. //
  1114. // f must not retain references to key and/or value after returning.
  1115. // Copy key and/or value contents before returning if you need retaining them.
  1116. //
  1117. // This function is slightly slower than VisitAll because it has to reparse the
  1118. // raw headers to get the order.
  1119. //
  1120. // Deprecated: Use AllInOrder instead.
  1121. func (h *RequestHeader) VisitAllInOrder(f func(key, value []byte)) {
  1122. h.AllInOrder()(func(key, value []byte) bool {
  1123. f(key, value)
  1124. return true
  1125. })
  1126. }
  1127. // Del deletes header with the given key.
  1128. func (h *ResponseHeader) Del(key string) {
  1129. h.bufK = getHeaderKeyBytes(h.bufK, key, h.disableNormalizing)
  1130. h.del(h.bufK)
  1131. }
  1132. // DelBytes deletes header with the given key.
  1133. func (h *ResponseHeader) DelBytes(key []byte) {
  1134. h.bufK = append(h.bufK[:0], key...)
  1135. normalizeHeaderKey(h.bufK, h.disableNormalizing || bytes.IndexByte(key, ' ') != -1)
  1136. h.del(h.bufK)
  1137. }
  1138. func (h *ResponseHeader) del(key []byte) {
  1139. switch string(key) {
  1140. case HeaderContentType:
  1141. h.contentType = h.contentType[:0]
  1142. case HeaderContentEncoding:
  1143. h.contentEncoding = h.contentEncoding[:0]
  1144. case HeaderServer:
  1145. h.server = h.server[:0]
  1146. case HeaderSetCookie:
  1147. h.cookies = h.cookies[:0]
  1148. case HeaderContentLength:
  1149. h.contentLength = 0
  1150. h.contentLengthBytes = h.contentLengthBytes[:0]
  1151. case HeaderConnection:
  1152. h.connectionClose = false
  1153. case HeaderTrailer:
  1154. h.trailer = h.trailer[:0]
  1155. }
  1156. h.h = delAllArgs(h.h, b2s(key))
  1157. }
  1158. // Del deletes header with the given key.
  1159. func (h *RequestHeader) Del(key string) {
  1160. h.bufK = getHeaderKeyBytes(h.bufK, key, h.disableNormalizing)
  1161. h.del(h.bufK)
  1162. }
  1163. // DelBytes deletes header with the given key.
  1164. func (h *RequestHeader) DelBytes(key []byte) {
  1165. h.bufK = append(h.bufK[:0], key...)
  1166. normalizeHeaderKey(h.bufK, h.disableNormalizing || bytes.IndexByte(key, ' ') != -1)
  1167. h.del(h.bufK)
  1168. }
  1169. func (h *RequestHeader) del(key []byte) {
  1170. switch string(key) {
  1171. case HeaderHost:
  1172. h.host = h.host[:0]
  1173. case HeaderContentType:
  1174. h.contentType = h.contentType[:0]
  1175. case HeaderUserAgent:
  1176. h.userAgent = h.userAgent[:0]
  1177. case HeaderCookie:
  1178. h.cookies = h.cookies[:0]
  1179. case HeaderContentLength:
  1180. h.contentLength = 0
  1181. h.contentLengthBytes = h.contentLengthBytes[:0]
  1182. case HeaderConnection:
  1183. h.connectionClose = false
  1184. case HeaderTrailer:
  1185. h.trailer = h.trailer[:0]
  1186. }
  1187. h.h = delAllArgs(h.h, b2s(key))
  1188. }
  1189. // setSpecialHeader handles special headers and return true when a header is processed.
  1190. func (h *ResponseHeader) setSpecialHeader(key, value []byte) bool {
  1191. if len(key) == 0 {
  1192. return false
  1193. }
  1194. switch key[0] | 0x20 {
  1195. case 'c':
  1196. switch {
  1197. case caseInsensitiveCompare(strContentType, key):
  1198. h.SetContentTypeBytes(value)
  1199. return true
  1200. case caseInsensitiveCompare(strContentLength, key):
  1201. if contentLength, err := parseContentLength(value); err == nil {
  1202. h.contentLength = contentLength
  1203. h.contentLengthBytes = append(h.contentLengthBytes[:0], value...)
  1204. }
  1205. return true
  1206. case caseInsensitiveCompare(strContentEncoding, key):
  1207. h.SetContentEncodingBytes(value)
  1208. return true
  1209. case caseInsensitiveCompare(strConnection, key):
  1210. if bytes.Equal(strClose, value) {
  1211. h.SetConnectionClose()
  1212. } else {
  1213. h.ResetConnectionClose()
  1214. h.setNonSpecial(key, value)
  1215. }
  1216. return true
  1217. }
  1218. case 's':
  1219. if caseInsensitiveCompare(strServer, key) {
  1220. h.SetServerBytes(value)
  1221. return true
  1222. } else if caseInsensitiveCompare(strSetCookie, key) {
  1223. var kv *argsKV
  1224. h.cookies, kv = allocArg(h.cookies)
  1225. kv.key = getCookieKey(kv.key, value)
  1226. kv.value = append(kv.value[:0], value...)
  1227. return true
  1228. }
  1229. case 't':
  1230. if caseInsensitiveCompare(strTransferEncoding, key) {
  1231. // Transfer-Encoding is managed automatically.
  1232. return true
  1233. } else if caseInsensitiveCompare(strTrailer, key) {
  1234. _ = h.SetTrailerBytes(value)
  1235. return true
  1236. }
  1237. case 'd':
  1238. if caseInsensitiveCompare(strDate, key) {
  1239. // Date is managed automatically.
  1240. return true
  1241. }
  1242. }
  1243. return false
  1244. }
  1245. // setNonSpecial directly put into map i.e. not a basic header.
  1246. func (h *header) setNonSpecial(key, value []byte) {
  1247. h.h = setArgBytes(h.h, key, value, argsHasValue)
  1248. }
  1249. // setSpecialHeader handles special headers and return true when a header is processed.
  1250. func (h *RequestHeader) setSpecialHeader(key, value []byte) bool {
  1251. if len(key) == 0 || h.disableSpecialHeader {
  1252. return false
  1253. }
  1254. switch key[0] | 0x20 {
  1255. case 'c':
  1256. switch {
  1257. case caseInsensitiveCompare(strContentType, key):
  1258. h.SetContentTypeBytes(value)
  1259. return true
  1260. case caseInsensitiveCompare(strContentLength, key):
  1261. if contentLength, err := parseContentLength(value); err == nil {
  1262. h.contentLength = contentLength
  1263. h.contentLengthBytes = append(h.contentLengthBytes[:0], value...)
  1264. }
  1265. return true
  1266. case caseInsensitiveCompare(strConnection, key):
  1267. if bytes.Equal(strClose, value) {
  1268. h.SetConnectionClose()
  1269. } else {
  1270. h.ResetConnectionClose()
  1271. h.setNonSpecial(key, value)
  1272. }
  1273. return true
  1274. case caseInsensitiveCompare(strCookie, key):
  1275. h.collectCookies()
  1276. h.cookies = parseRequestCookies(h.cookies, value)
  1277. return true
  1278. }
  1279. case 't':
  1280. if caseInsensitiveCompare(strTransferEncoding, key) {
  1281. // Transfer-Encoding is managed automatically.
  1282. return true
  1283. } else if caseInsensitiveCompare(strTrailer, key) {
  1284. _ = h.SetTrailerBytes(value)
  1285. return true
  1286. }
  1287. case 'h':
  1288. if caseInsensitiveCompare(strHost, key) {
  1289. h.SetHostBytes(value)
  1290. return true
  1291. }
  1292. case 'u':
  1293. if caseInsensitiveCompare(strUserAgent, key) {
  1294. h.SetUserAgentBytes(value)
  1295. return true
  1296. }
  1297. }
  1298. return false
  1299. }
  1300. // Add adds the given 'key: value' header.
  1301. //
  1302. // Multiple headers with the same key may be added with this function.
  1303. // Use Set for setting a single header for the given key.
  1304. //
  1305. // the Content-Type, Content-Length, Connection, Server, Transfer-Encoding
  1306. // and Date headers can only be set once and will overwrite the previous value,
  1307. // while Set-Cookie will not clear previous cookies.
  1308. //
  1309. // If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details),
  1310. // it will be sent after the chunked response body.
  1311. func (h *ResponseHeader) Add(key, value string) {
  1312. h.AddBytesKV(s2b(key), s2b(value))
  1313. }
  1314. // AddBytesK adds the given 'key: value' header.
  1315. //
  1316. // Multiple headers with the same key may be added with this function.
  1317. // Use SetBytesK for setting a single header for the given key.
  1318. //
  1319. // the Content-Type, Content-Length, Connection, Server, Transfer-Encoding
  1320. // and Date headers can only be set once and will overwrite the previous value,
  1321. // while Set-Cookie will not clear previous cookies.
  1322. //
  1323. // If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details),
  1324. // it will be sent after the chunked response body.
  1325. func (h *ResponseHeader) AddBytesK(key []byte, value string) {
  1326. h.AddBytesKV(key, s2b(value))
  1327. }
  1328. // AddBytesV adds the given 'key: value' header.
  1329. //
  1330. // Multiple headers with the same key may be added with this function.
  1331. // Use SetBytesV for setting a single header for the given key.
  1332. //
  1333. // the Content-Type, Content-Length, Connection, Server, Transfer-Encoding
  1334. // and Date headers can only be set once and will overwrite the previous value,
  1335. // while Set-Cookie will not clear previous cookies.
  1336. //
  1337. // If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details),
  1338. // it will be sent after the chunked response body.
  1339. func (h *ResponseHeader) AddBytesV(key string, value []byte) {
  1340. h.AddBytesKV(s2b(key), value)
  1341. }
  1342. // AddBytesKV adds the given 'key: value' header.
  1343. //
  1344. // Multiple headers with the same key may be added with this function.
  1345. // Use SetBytesKV for setting a single header for the given key.
  1346. //
  1347. // the Content-Type, Content-Length, Connection, Server, Transfer-Encoding
  1348. // and Date headers can only be set once and will overwrite the previous value,
  1349. // while the Set-Cookie header will not clear previous cookies.
  1350. //
  1351. // If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details),
  1352. // it will be sent after the chunked response body.
  1353. func (h *ResponseHeader) AddBytesKV(key, value []byte) {
  1354. if h.setSpecialHeader(key, value) {
  1355. return
  1356. }
  1357. h.bufK = getHeaderKeyBytes(h.bufK, b2s(key), h.disableNormalizing)
  1358. h.h = appendArgBytes(h.h, h.bufK, value, argsHasValue)
  1359. }
  1360. // Set sets the given 'key: value' header.
  1361. //
  1362. // Please note that the Set-Cookie header will not clear previous cookies,
  1363. // use SetCookie instead to reset cookies.
  1364. //
  1365. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1366. // it will be sent after the chunked response body.
  1367. //
  1368. // Use Add for setting multiple header values under the same key.
  1369. func (h *ResponseHeader) Set(key, value string) {
  1370. h.bufK, h.bufV = initHeaderKV(h.bufK, h.bufV, key, value, h.disableNormalizing)
  1371. h.SetCanonical(h.bufK, h.bufV)
  1372. }
  1373. // SetBytesK sets the given 'key: value' header.
  1374. //
  1375. // Please note that the Set-Cookie header will not clear previous cookies,
  1376. // use SetCookie instead to reset cookies.
  1377. //
  1378. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1379. // it will be sent after the chunked response body.
  1380. //
  1381. // Use AddBytesK for setting multiple header values under the same key.
  1382. func (h *ResponseHeader) SetBytesK(key []byte, value string) {
  1383. h.bufV = append(h.bufV[:0], value...)
  1384. h.SetBytesKV(key, h.bufV)
  1385. }
  1386. // SetBytesV sets the given 'key: value' header.
  1387. //
  1388. // Please note that the Set-Cookie header will not clear previous cookies,
  1389. // use SetCookie instead to reset cookies.
  1390. //
  1391. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1392. // it will be sent after the chunked response body.
  1393. //
  1394. // Use AddBytesV for setting multiple header values under the same key.
  1395. func (h *ResponseHeader) SetBytesV(key string, value []byte) {
  1396. h.bufK = getHeaderKeyBytes(h.bufK, key, h.disableNormalizing)
  1397. h.SetCanonical(h.bufK, value)
  1398. }
  1399. // SetBytesKV sets the given 'key: value' header.
  1400. //
  1401. // Please note that the Set-Cookie header will not clear previous cookies,
  1402. // use SetCookie instead to reset cookies.
  1403. //
  1404. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1405. // it will be sent after the chunked response body.
  1406. //
  1407. // Use AddBytesKV for setting multiple header values under the same key.
  1408. func (h *ResponseHeader) SetBytesKV(key, value []byte) {
  1409. h.bufK = append(h.bufK[:0], key...)
  1410. normalizeHeaderKey(h.bufK, h.disableNormalizing || bytes.IndexByte(key, ' ') != -1)
  1411. h.SetCanonical(h.bufK, value)
  1412. }
  1413. // SetCanonical sets the given 'key: value' header assuming that
  1414. // key is in canonical form.
  1415. //
  1416. // Please note that the Set-Cookie header will not clear previous cookies,
  1417. // use SetCookie instead to reset cookies.
  1418. //
  1419. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1420. // it will be sent after the chunked response body.
  1421. func (h *ResponseHeader) SetCanonical(key, value []byte) {
  1422. if h.setSpecialHeader(key, value) {
  1423. return
  1424. }
  1425. h.setNonSpecial(key, value)
  1426. }
  1427. // SetCookie sets the given response cookie.
  1428. //
  1429. // It is safe re-using the cookie after the function returns.
  1430. func (h *ResponseHeader) SetCookie(cookie *Cookie) {
  1431. h.cookies = setArgBytes(h.cookies, cookie.Key(), cookie.Cookie(), argsHasValue)
  1432. }
  1433. // SetCookie sets 'key: value' cookies.
  1434. func (h *RequestHeader) SetCookie(key, value string) {
  1435. h.collectCookies()
  1436. h.cookies = setArg(h.cookies, key, value, argsHasValue)
  1437. }
  1438. // SetCookieBytesK sets 'key: value' cookies.
  1439. func (h *RequestHeader) SetCookieBytesK(key []byte, value string) {
  1440. h.SetCookie(b2s(key), value)
  1441. }
  1442. // SetCookieBytesKV sets 'key: value' cookies.
  1443. func (h *RequestHeader) SetCookieBytesKV(key, value []byte) {
  1444. h.SetCookie(b2s(key), b2s(value))
  1445. }
  1446. // DelClientCookie instructs the client to remove the given cookie.
  1447. // This doesn't work for a cookie with specific domain or path,
  1448. // you should delete it manually like:
  1449. //
  1450. // c := AcquireCookie()
  1451. // c.SetKey(key)
  1452. // c.SetDomain("example.com")
  1453. // c.SetPath("/path")
  1454. // c.SetExpire(CookieExpireDelete)
  1455. // h.SetCookie(c)
  1456. // ReleaseCookie(c)
  1457. //
  1458. // Use DelCookie if you want just removing the cookie from response header.
  1459. func (h *ResponseHeader) DelClientCookie(key string) {
  1460. h.DelCookie(key)
  1461. c := AcquireCookie()
  1462. c.SetKey(key)
  1463. c.SetExpire(CookieExpireDelete)
  1464. h.SetCookie(c)
  1465. ReleaseCookie(c)
  1466. }
  1467. // DelClientCookieBytes instructs the client to remove the given cookie.
  1468. // This doesn't work for a cookie with specific domain or path,
  1469. // you should delete it manually like:
  1470. //
  1471. // c := AcquireCookie()
  1472. // c.SetKey(key)
  1473. // c.SetDomain("example.com")
  1474. // c.SetPath("/path")
  1475. // c.SetExpire(CookieExpireDelete)
  1476. // h.SetCookie(c)
  1477. // ReleaseCookie(c)
  1478. //
  1479. // Use DelCookieBytes if you want just removing the cookie from response header.
  1480. func (h *ResponseHeader) DelClientCookieBytes(key []byte) {
  1481. h.DelClientCookie(b2s(key))
  1482. }
  1483. // DelCookie removes cookie under the given key from response header.
  1484. //
  1485. // Note that DelCookie doesn't remove the cookie from the client.
  1486. // Use DelClientCookie instead.
  1487. func (h *ResponseHeader) DelCookie(key string) {
  1488. h.cookies = delAllArgs(h.cookies, key)
  1489. }
  1490. // DelCookieBytes removes cookie under the given key from response header.
  1491. //
  1492. // Note that DelCookieBytes doesn't remove the cookie from the client.
  1493. // Use DelClientCookieBytes instead.
  1494. func (h *ResponseHeader) DelCookieBytes(key []byte) {
  1495. h.DelCookie(b2s(key))
  1496. }
  1497. // DelCookie removes cookie under the given key.
  1498. func (h *RequestHeader) DelCookie(key string) {
  1499. h.collectCookies()
  1500. h.cookies = delAllArgs(h.cookies, key)
  1501. }
  1502. // DelCookieBytes removes cookie under the given key.
  1503. func (h *RequestHeader) DelCookieBytes(key []byte) {
  1504. h.DelCookie(b2s(key))
  1505. }
  1506. // DelAllCookies removes all the cookies from response headers.
  1507. func (h *ResponseHeader) DelAllCookies() {
  1508. h.cookies = h.cookies[:0]
  1509. }
  1510. // DelAllCookies removes all the cookies from request headers.
  1511. func (h *RequestHeader) DelAllCookies() {
  1512. h.collectCookies()
  1513. h.cookies = h.cookies[:0]
  1514. }
  1515. // Add adds the given 'key: value' header.
  1516. //
  1517. // Multiple headers with the same key may be added with this function.
  1518. // Use Set for setting a single header for the given key.
  1519. //
  1520. // If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details),
  1521. // it will be sent after the chunked request body.
  1522. func (h *RequestHeader) Add(key, value string) {
  1523. h.AddBytesKV(s2b(key), s2b(value))
  1524. }
  1525. // AddBytesK adds the given 'key: value' header.
  1526. //
  1527. // Multiple headers with the same key may be added with this function.
  1528. // Use SetBytesK for setting a single header for the given key.
  1529. //
  1530. // If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details),
  1531. // it will be sent after the chunked request body.
  1532. func (h *RequestHeader) AddBytesK(key []byte, value string) {
  1533. h.AddBytesKV(key, s2b(value))
  1534. }
  1535. // AddBytesV adds the given 'key: value' header.
  1536. //
  1537. // Multiple headers with the same key may be added with this function.
  1538. // Use SetBytesV for setting a single header for the given key.
  1539. //
  1540. // If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details),
  1541. // it will be sent after the chunked request body.
  1542. func (h *RequestHeader) AddBytesV(key string, value []byte) {
  1543. h.AddBytesKV(s2b(key), value)
  1544. }
  1545. // AddBytesKV adds the given 'key: value' header.
  1546. //
  1547. // Multiple headers with the same key may be added with this function.
  1548. // Use SetBytesKV for setting a single header for the given key.
  1549. //
  1550. // the Content-Type, Content-Length, Connection, Transfer-Encoding,
  1551. // Host and User-Agent headers can only be set once and will overwrite
  1552. // the previous value, while the Cookie header will not clear previous cookies.
  1553. //
  1554. // If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details),
  1555. // it will be sent after the chunked request body.
  1556. func (h *RequestHeader) AddBytesKV(key, value []byte) {
  1557. if h.setSpecialHeader(key, value) {
  1558. return
  1559. }
  1560. h.bufK = getHeaderKeyBytes(h.bufK, b2s(key), h.disableNormalizing)
  1561. h.h = appendArgBytes(h.h, h.bufK, value, argsHasValue)
  1562. }
  1563. // Set sets the given 'key: value' header.
  1564. //
  1565. // Please note that the Cookie header will not clear previous cookies,
  1566. // delete cookies before calling in order to reset cookies.
  1567. //
  1568. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1569. // it will be sent after the chunked request body.
  1570. //
  1571. // Use Add for setting multiple header values under the same key.
  1572. func (h *RequestHeader) Set(key, value string) {
  1573. h.bufK, h.bufV = initHeaderKV(h.bufK, h.bufV, key, value, h.disableNormalizing)
  1574. h.SetCanonical(h.bufK, h.bufV)
  1575. }
  1576. // SetBytesK sets the given 'key: value' header.
  1577. //
  1578. // Please note that the Cookie header will not clear previous cookies,
  1579. // delete cookies before calling in order to reset cookies.
  1580. //
  1581. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1582. // it will be sent after the chunked request body.
  1583. //
  1584. // Use AddBytesK for setting multiple header values under the same key.
  1585. func (h *RequestHeader) SetBytesK(key []byte, value string) {
  1586. h.bufV = append(h.bufV[:0], value...)
  1587. h.SetBytesKV(key, h.bufV)
  1588. }
  1589. // SetBytesV sets the given 'key: value' header.
  1590. //
  1591. // Please note that the Cookie header will not clear previous cookies,
  1592. // delete cookies before calling in order to reset cookies.
  1593. //
  1594. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1595. // it will be sent after the chunked request body.
  1596. //
  1597. // Use AddBytesV for setting multiple header values under the same key.
  1598. func (h *RequestHeader) SetBytesV(key string, value []byte) {
  1599. h.bufK = getHeaderKeyBytes(h.bufK, key, h.disableNormalizing)
  1600. h.SetCanonical(h.bufK, value)
  1601. }
  1602. // SetBytesKV sets the given 'key: value' header.
  1603. //
  1604. // Please note that the Cookie header will not clear previous cookies,
  1605. // delete cookies before calling in order to reset cookies.
  1606. //
  1607. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1608. // it will be sent after the chunked request body.
  1609. //
  1610. // Use AddBytesKV for setting multiple header values under the same key.
  1611. func (h *RequestHeader) SetBytesKV(key, value []byte) {
  1612. h.bufK = append(h.bufK[:0], key...)
  1613. normalizeHeaderKey(h.bufK, h.disableNormalizing || bytes.IndexByte(key, ' ') != -1)
  1614. h.SetCanonical(h.bufK, value)
  1615. }
  1616. // SetCanonical sets the given 'key: value' header assuming that
  1617. // key is in canonical form.
  1618. //
  1619. // Please note that the Cookie header will not clear previous cookies,
  1620. // delete cookies before calling in order to reset cookies.
  1621. //
  1622. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1623. // it will be sent after the chunked request body.
  1624. func (h *RequestHeader) SetCanonical(key, value []byte) {
  1625. if h.setSpecialHeader(key, value) {
  1626. return
  1627. }
  1628. h.setNonSpecial(key, value)
  1629. }
  1630. // Peek returns header value for the given key.
  1631. //
  1632. // The returned value is valid until the response is released,
  1633. // either though ReleaseResponse or your request handler returning.
  1634. // Do not store references to the returned value. Make copies instead.
  1635. func (h *ResponseHeader) Peek(key string) []byte {
  1636. h.bufK = getHeaderKeyBytes(h.bufK, key, h.disableNormalizing)
  1637. return h.peek(h.bufK)
  1638. }
  1639. // PeekBytes returns header value for the given key.
  1640. //
  1641. // The returned value is valid until the response is released,
  1642. // either though ReleaseResponse or your request handler returning.
  1643. // Do not store references to returned value. Make copies instead.
  1644. func (h *ResponseHeader) PeekBytes(key []byte) []byte {
  1645. h.bufK = append(h.bufK[:0], key...)
  1646. normalizeHeaderKey(h.bufK, h.disableNormalizing || bytes.IndexByte(key, ' ') != -1)
  1647. return h.peek(h.bufK)
  1648. }
  1649. // Peek returns header value for the given key.
  1650. //
  1651. // The returned value is valid until the request is released,
  1652. // either though ReleaseRequest or your request handler returning.
  1653. // Do not store references to returned value. Make copies instead.
  1654. func (h *RequestHeader) Peek(key string) []byte {
  1655. h.bufK = getHeaderKeyBytes(h.bufK, key, h.disableNormalizing)
  1656. return h.peek(h.bufK)
  1657. }
  1658. // PeekBytes returns header value for the given key.
  1659. //
  1660. // The returned value is valid until the request is released,
  1661. // either though ReleaseRequest or your request handler returning.
  1662. // Do not store references to returned value. Make copies instead.
  1663. func (h *RequestHeader) PeekBytes(key []byte) []byte {
  1664. h.bufK = append(h.bufK[:0], key...)
  1665. normalizeHeaderKey(h.bufK, h.disableNormalizing || bytes.IndexByte(key, ' ') != -1)
  1666. return h.peek(h.bufK)
  1667. }
  1668. func (h *ResponseHeader) peek(key []byte) []byte {
  1669. switch string(key) {
  1670. case HeaderContentType:
  1671. return h.ContentType()
  1672. case HeaderContentEncoding:
  1673. return h.ContentEncoding()
  1674. case HeaderServer:
  1675. return h.Server()
  1676. case HeaderConnection:
  1677. if h.ConnectionClose() {
  1678. return strClose
  1679. }
  1680. return peekArgBytes(h.h, key)
  1681. case HeaderContentLength:
  1682. return h.contentLengthBytes
  1683. case HeaderSetCookie:
  1684. return appendResponseCookieBytes(nil, h.cookies)
  1685. case HeaderTrailer:
  1686. return appendTrailerBytes(nil, h.trailer, strCommaSpace)
  1687. default:
  1688. return peekArgBytes(h.h, key)
  1689. }
  1690. }
  1691. func (h *RequestHeader) peek(key []byte) []byte {
  1692. switch string(key) {
  1693. case HeaderHost:
  1694. return h.Host()
  1695. case HeaderContentType:
  1696. return h.ContentType()
  1697. case HeaderUserAgent:
  1698. return h.UserAgent()
  1699. case HeaderConnection:
  1700. if h.ConnectionClose() {
  1701. return strClose
  1702. }
  1703. return peekArgBytes(h.h, key)
  1704. case HeaderContentLength:
  1705. return h.contentLengthBytes
  1706. case HeaderCookie:
  1707. if h.cookiesCollected {
  1708. return appendRequestCookieBytes(nil, h.cookies)
  1709. }
  1710. return peekArgBytes(h.h, key)
  1711. case HeaderTrailer:
  1712. return appendTrailerBytes(nil, h.trailer, strCommaSpace)
  1713. default:
  1714. return peekArgBytes(h.h, key)
  1715. }
  1716. }
  1717. // PeekAll returns all header value for the given key.
  1718. //
  1719. // The returned value is valid until the request is released,
  1720. // either though ReleaseRequest or your request handler returning.
  1721. // Any future calls to the Peek* will modify the returned value.
  1722. // Do not store references to returned value. Make copies instead.
  1723. func (h *RequestHeader) PeekAll(key string) [][]byte {
  1724. h.bufK = getHeaderKeyBytes(h.bufK, key, h.disableNormalizing)
  1725. return h.peekAll(h.bufK)
  1726. }
  1727. func (h *RequestHeader) peekAll(key []byte) [][]byte {
  1728. h.mulHeader = h.mulHeader[:0]
  1729. switch string(key) {
  1730. case HeaderHost:
  1731. if host := h.Host(); len(host) > 0 {
  1732. h.mulHeader = append(h.mulHeader, host)
  1733. }
  1734. case HeaderContentType:
  1735. if contentType := h.ContentType(); len(contentType) > 0 {
  1736. h.mulHeader = append(h.mulHeader, contentType)
  1737. }
  1738. case HeaderUserAgent:
  1739. if ua := h.UserAgent(); len(ua) > 0 {
  1740. h.mulHeader = append(h.mulHeader, ua)
  1741. }
  1742. case HeaderConnection:
  1743. if h.ConnectionClose() {
  1744. h.mulHeader = append(h.mulHeader, strClose)
  1745. } else {
  1746. h.mulHeader = peekAllArgBytesToDst(h.mulHeader, h.h, key)
  1747. }
  1748. case HeaderContentLength:
  1749. h.mulHeader = append(h.mulHeader, h.contentLengthBytes)
  1750. case HeaderCookie:
  1751. if h.cookiesCollected {
  1752. h.mulHeader = append(h.mulHeader, appendRequestCookieBytes(nil, h.cookies))
  1753. } else {
  1754. h.mulHeader = peekAllArgBytesToDst(h.mulHeader, h.h, key)
  1755. }
  1756. case HeaderTrailer:
  1757. h.mulHeader = append(h.mulHeader, appendTrailerBytes(nil, h.trailer, strCommaSpace))
  1758. default:
  1759. h.mulHeader = peekAllArgBytesToDst(h.mulHeader, h.h, key)
  1760. }
  1761. return h.mulHeader
  1762. }
  1763. // PeekAll returns all header value for the given key.
  1764. //
  1765. // The returned value is valid until the request is released,
  1766. // either though ReleaseResponse or your request handler returning.
  1767. // Any future calls to the Peek* will modify the returned value.
  1768. // Do not store references to returned value. Make copies instead.
  1769. func (h *ResponseHeader) PeekAll(key string) [][]byte {
  1770. h.bufK = getHeaderKeyBytes(h.bufK, key, h.disableNormalizing)
  1771. return h.peekAll(h.bufK)
  1772. }
  1773. func (h *ResponseHeader) peekAll(key []byte) [][]byte {
  1774. h.mulHeader = h.mulHeader[:0]
  1775. switch string(key) {
  1776. case HeaderContentType:
  1777. if contentType := h.ContentType(); len(contentType) > 0 {
  1778. h.mulHeader = append(h.mulHeader, contentType)
  1779. }
  1780. case HeaderContentEncoding:
  1781. if contentEncoding := h.ContentEncoding(); len(contentEncoding) > 0 {
  1782. h.mulHeader = append(h.mulHeader, contentEncoding)
  1783. }
  1784. case HeaderServer:
  1785. if server := h.Server(); len(server) > 0 {
  1786. h.mulHeader = append(h.mulHeader, server)
  1787. }
  1788. case HeaderConnection:
  1789. if h.ConnectionClose() {
  1790. h.mulHeader = append(h.mulHeader, strClose)
  1791. } else {
  1792. h.mulHeader = peekAllArgBytesToDst(h.mulHeader, h.h, key)
  1793. }
  1794. case HeaderContentLength:
  1795. h.mulHeader = append(h.mulHeader, h.contentLengthBytes)
  1796. case HeaderSetCookie:
  1797. h.mulHeader = append(h.mulHeader, appendResponseCookieBytes(nil, h.cookies))
  1798. case HeaderTrailer:
  1799. h.mulHeader = append(h.mulHeader, appendTrailerBytes(nil, h.trailer, strCommaSpace))
  1800. default:
  1801. h.mulHeader = peekAllArgBytesToDst(h.mulHeader, h.h, key)
  1802. }
  1803. return h.mulHeader
  1804. }
  1805. // PeekKeys return all header keys.
  1806. //
  1807. // The returned value is valid until the request is released,
  1808. // either though ReleaseRequest or your request handler returning.
  1809. // Any future calls to the Peek* will modify the returned value.
  1810. // Do not store references to returned value. Make copies instead.
  1811. func (h *RequestHeader) PeekKeys() [][]byte {
  1812. h.mulHeader = h.mulHeader[:0]
  1813. for key := range h.All() {
  1814. h.mulHeader = append(h.mulHeader, key)
  1815. }
  1816. return h.mulHeader
  1817. }
  1818. // PeekKeys return all header keys.
  1819. //
  1820. // The returned value is valid until the request is released,
  1821. // either though ReleaseRequest or your request handler returning.
  1822. // Any future calls to the Peek* will modify the returned value.
  1823. // Do not store references to returned value. Make copies instead.
  1824. func (h *ResponseHeader) PeekKeys() [][]byte {
  1825. h.mulHeader = h.mulHeader[:0]
  1826. for key := range h.All() {
  1827. h.mulHeader = append(h.mulHeader, key)
  1828. }
  1829. return h.mulHeader
  1830. }
  1831. // PeekTrailerKeys return all trailer keys.
  1832. //
  1833. // The returned value is valid until the request is released,
  1834. // either though ReleaseResponse or your request handler returning.
  1835. // Any future calls to the Peek* will modify the returned value.
  1836. // Do not store references to returned value. Make copies instead.
  1837. func (h *header) PeekTrailerKeys() [][]byte {
  1838. h.mulHeader = copyTrailer(h.mulHeader, h.trailer)
  1839. return h.mulHeader
  1840. }
  1841. // Cookie returns cookie for the given key.
  1842. func (h *RequestHeader) Cookie(key string) []byte {
  1843. h.collectCookies()
  1844. return peekArgStr(h.cookies, key)
  1845. }
  1846. // CookieBytes returns cookie for the given key.
  1847. func (h *RequestHeader) CookieBytes(key []byte) []byte {
  1848. h.collectCookies()
  1849. return peekArgBytes(h.cookies, key)
  1850. }
  1851. // Cookie fills cookie for the given cookie.Key.
  1852. //
  1853. // Returns false if cookie with the given cookie.Key is missing.
  1854. func (h *ResponseHeader) Cookie(cookie *Cookie) bool {
  1855. v := peekArgBytes(h.cookies, cookie.Key())
  1856. if v == nil {
  1857. return false
  1858. }
  1859. cookie.ParseBytes(v) //nolint:errcheck
  1860. return true
  1861. }
  1862. // Read reads response header from r.
  1863. //
  1864. // io.EOF is returned if r is closed before reading the first header byte.
  1865. func (h *ResponseHeader) Read(r *bufio.Reader) error {
  1866. n := 1
  1867. for {
  1868. err := h.tryRead(r, n)
  1869. if err == nil {
  1870. return nil
  1871. }
  1872. if err != errNeedMore {
  1873. h.resetSkipNormalize()
  1874. return err
  1875. }
  1876. n = r.Buffered() + 1
  1877. }
  1878. }
  1879. func (h *ResponseHeader) tryRead(r *bufio.Reader, n int) error {
  1880. h.resetSkipNormalize()
  1881. b, err := r.Peek(n)
  1882. if len(b) == 0 {
  1883. // Return ErrTimeout on any timeout.
  1884. if x, ok := err.(interface{ Timeout() bool }); ok && x.Timeout() {
  1885. return ErrTimeout
  1886. }
  1887. // treat all other errors on the first byte read as EOF
  1888. if n == 1 || err == io.EOF {
  1889. return io.EOF
  1890. }
  1891. // This is for go 1.6 bug. See https://github.com/golang/go/issues/14121 .
  1892. if err == bufio.ErrBufferFull {
  1893. if h.secureErrorLogMessage {
  1894. return &ErrSmallBuffer{
  1895. error: errors.New("error when reading response headers"),
  1896. }
  1897. }
  1898. return &ErrSmallBuffer{
  1899. error: fmt.Errorf("error when reading response headers: %w", errSmallBuffer),
  1900. }
  1901. }
  1902. return fmt.Errorf("error when reading response headers: %w", err)
  1903. }
  1904. b = mustPeekBuffered(r)
  1905. headersLen, errParse := h.parse(b)
  1906. if errParse != nil {
  1907. return headerError("response", err, errParse, b, h.secureErrorLogMessage)
  1908. }
  1909. mustDiscard(r, headersLen)
  1910. return nil
  1911. }
  1912. // ReadTrailer reads response trailer header from r.
  1913. //
  1914. // io.EOF is returned if r is closed before reading the first byte.
  1915. func (h *header) ReadTrailer(r *bufio.Reader) error {
  1916. n := 1
  1917. for {
  1918. err := h.tryReadTrailer(r, n)
  1919. if err == nil {
  1920. return nil
  1921. }
  1922. if err != errNeedMore {
  1923. return err
  1924. }
  1925. n = r.Buffered() + 1
  1926. }
  1927. }
  1928. func (h *header) tryReadTrailer(r *bufio.Reader, n int) error {
  1929. b, err := r.Peek(n)
  1930. if len(b) == 0 {
  1931. // Return ErrTimeout on any timeout.
  1932. if x, ok := err.(interface{ Timeout() bool }); ok && x.Timeout() {
  1933. return ErrTimeout
  1934. }
  1935. if n == 1 || err == io.EOF {
  1936. return io.EOF
  1937. }
  1938. // This is for go 1.6 bug. See https://github.com/golang/go/issues/14121 .
  1939. if err == bufio.ErrBufferFull {
  1940. if h.secureErrorLogMessage {
  1941. return &ErrSmallBuffer{
  1942. error: errors.New("error when reading response trailer"),
  1943. }
  1944. }
  1945. return &ErrSmallBuffer{
  1946. error: fmt.Errorf("error when reading response trailer: %w", errSmallBuffer),
  1947. }
  1948. }
  1949. return fmt.Errorf("error when reading response trailer: %w", err)
  1950. }
  1951. b = mustPeekBuffered(r)
  1952. hh, headersLen, errParse := parseTrailer(b, h.h, h.disableNormalizing)
  1953. h.h = hh
  1954. if errParse != nil {
  1955. if err == io.EOF {
  1956. return err
  1957. }
  1958. return headerError("response", err, errParse, b, h.secureErrorLogMessage)
  1959. }
  1960. mustDiscard(r, headersLen)
  1961. return nil
  1962. }
  1963. func headerError(typ string, err, errParse error, b []byte, secureErrorLogMessage bool) error {
  1964. if errParse != errNeedMore {
  1965. return headerErrorMsg(typ, errParse, b, secureErrorLogMessage)
  1966. }
  1967. if err == nil {
  1968. return errNeedMore
  1969. }
  1970. // Buggy servers may leave trailing CRLFs after http body.
  1971. // Treat this case as EOF.
  1972. if isOnlyCRLF(b) {
  1973. return io.EOF
  1974. }
  1975. if err != bufio.ErrBufferFull {
  1976. return headerErrorMsg(typ, err, b, secureErrorLogMessage)
  1977. }
  1978. return &ErrSmallBuffer{
  1979. error: headerErrorMsg(typ, errSmallBuffer, b, secureErrorLogMessage),
  1980. }
  1981. }
  1982. func headerErrorMsg(typ string, err error, b []byte, secureErrorLogMessage bool) error {
  1983. if secureErrorLogMessage {
  1984. return fmt.Errorf("error when reading %s headers: %w. Buffer size=%d", typ, err, len(b))
  1985. }
  1986. return fmt.Errorf("error when reading %s headers: %w. Buffer size=%d, contents: %s", typ, err, len(b), bufferSnippet(b))
  1987. }
  1988. // Read reads request header from r.
  1989. //
  1990. // io.EOF is returned if r is closed before reading the first header byte.
  1991. func (h *RequestHeader) Read(r *bufio.Reader) error {
  1992. return h.readLoop(r, true)
  1993. }
  1994. // readLoop reads request header from r optionally loops until it has enough data.
  1995. //
  1996. // io.EOF is returned if r is closed before reading the first header byte.
  1997. func (h *RequestHeader) readLoop(r *bufio.Reader, waitForMore bool) error {
  1998. n := 1
  1999. for {
  2000. err := h.tryRead(r, n)
  2001. if err == nil {
  2002. return nil
  2003. }
  2004. if !waitForMore || err != errNeedMore {
  2005. h.resetSkipNormalize()
  2006. return err
  2007. }
  2008. n = r.Buffered() + 1
  2009. }
  2010. }
  2011. func (h *RequestHeader) tryRead(r *bufio.Reader, n int) error {
  2012. h.resetSkipNormalize()
  2013. b, err := r.Peek(n)
  2014. if len(b) == 0 {
  2015. if err == io.EOF {
  2016. return err
  2017. }
  2018. if err == nil {
  2019. panic("bufio.Reader.Peek() returned nil, nil")
  2020. }
  2021. // This is for go 1.6 bug. See https://github.com/golang/go/issues/14121 .
  2022. if err == bufio.ErrBufferFull {
  2023. return &ErrSmallBuffer{
  2024. error: fmt.Errorf("error when reading request headers: %w (n=%d, r.Buffered()=%d)", errSmallBuffer, n, r.Buffered()),
  2025. }
  2026. }
  2027. // n == 1 on the first read for the request.
  2028. if n == 1 {
  2029. // We didn't read a single byte.
  2030. return ErrNothingRead{error: err}
  2031. }
  2032. return fmt.Errorf("error when reading request headers: %w", err)
  2033. }
  2034. b = mustPeekBuffered(r)
  2035. headersLen, errParse := h.parse(b)
  2036. if errParse != nil {
  2037. return headerError("request", err, errParse, b, h.secureErrorLogMessage)
  2038. }
  2039. mustDiscard(r, headersLen)
  2040. return nil
  2041. }
  2042. func bufferSnippet(b []byte) string {
  2043. n := len(b)
  2044. start := 200
  2045. end := n - start
  2046. if start >= end {
  2047. start = n
  2048. end = n
  2049. }
  2050. bStart, bEnd := b[:start], b[end:]
  2051. if len(bEnd) == 0 {
  2052. return fmt.Sprintf("%q", b)
  2053. }
  2054. return fmt.Sprintf("%q...%q", bStart, bEnd)
  2055. }
  2056. func isOnlyCRLF(b []byte) bool {
  2057. for _, ch := range b {
  2058. if ch != rChar && ch != nChar {
  2059. return false
  2060. }
  2061. }
  2062. return true
  2063. }
  2064. func updateServerDate() {
  2065. refreshServerDate()
  2066. go func() {
  2067. for {
  2068. time.Sleep(time.Second)
  2069. refreshServerDate()
  2070. }
  2071. }()
  2072. }
  2073. var (
  2074. serverDate atomic.Value
  2075. serverDateOnce sync.Once // serverDateOnce.Do(updateServerDate)
  2076. )
  2077. func refreshServerDate() {
  2078. b := AppendHTTPDate(nil, time.Now())
  2079. serverDate.Store(b)
  2080. }
  2081. // Write writes response header to w.
  2082. func (h *ResponseHeader) Write(w *bufio.Writer) error {
  2083. _, err := w.Write(h.Header())
  2084. return err
  2085. }
  2086. // WriteTo writes response header to w.
  2087. //
  2088. // WriteTo implements io.WriterTo interface.
  2089. func (h *ResponseHeader) WriteTo(w io.Writer) (int64, error) {
  2090. n, err := w.Write(h.Header())
  2091. return int64(n), err
  2092. }
  2093. // Header returns response header representation.
  2094. //
  2095. // Headers that set as Trailer will not represent. Use TrailerHeader for trailers.
  2096. //
  2097. // The returned value is valid until the request is released,
  2098. // either though ReleaseRequest or your request handler returning.
  2099. // Do not store references to returned value. Make copies instead.
  2100. func (h *ResponseHeader) Header() []byte {
  2101. h.bufV = h.AppendBytes(h.bufV[:0])
  2102. return h.bufV
  2103. }
  2104. // writeTrailer writes response trailer to w.
  2105. func (h *ResponseHeader) writeTrailer(w *bufio.Writer) error {
  2106. _, err := w.Write(h.TrailerHeader())
  2107. return err
  2108. }
  2109. // TrailerHeader returns response trailer header representation.
  2110. //
  2111. // Trailers will only be received with chunked transfer.
  2112. //
  2113. // The returned value is valid until the request is released,
  2114. // either though ReleaseRequest or your request handler returning.
  2115. // Do not store references to returned value. Make copies instead.
  2116. func (h *ResponseHeader) TrailerHeader() []byte {
  2117. h.bufV = h.bufV[:0]
  2118. for _, t := range h.trailer {
  2119. value := h.peek(t)
  2120. h.bufV = appendHeaderLine(h.bufV, t, value)
  2121. }
  2122. h.bufV = append(h.bufV, strCRLF...)
  2123. return h.bufV
  2124. }
  2125. // String returns response header representation.
  2126. func (h *ResponseHeader) String() string {
  2127. return string(h.Header())
  2128. }
  2129. // appendStatusLine appends the response status line to dst and returns
  2130. // the extended dst.
  2131. func (h *ResponseHeader) appendStatusLine(dst []byte) []byte {
  2132. statusCode := h.StatusCode()
  2133. if statusCode < 0 {
  2134. statusCode = StatusOK
  2135. }
  2136. return formatStatusLine(dst, h.Protocol(), statusCode, h.StatusMessage())
  2137. }
  2138. // AppendBytes appends response header representation to dst and returns
  2139. // the extended dst.
  2140. func (h *ResponseHeader) AppendBytes(dst []byte) []byte {
  2141. dst = h.appendStatusLine(dst[:0])
  2142. server := h.Server()
  2143. if len(server) != 0 {
  2144. dst = appendHeaderLine(dst, strServer, server)
  2145. }
  2146. if !h.noDefaultDate {
  2147. serverDateOnce.Do(updateServerDate)
  2148. dst = appendHeaderLine(dst, strDate, serverDate.Load().([]byte))
  2149. }
  2150. // Append Content-Type only for non-zero responses
  2151. // or if it is explicitly set.
  2152. // See https://github.com/valyala/fasthttp/issues/28 .
  2153. if h.ContentLength() != 0 || len(h.contentType) > 0 {
  2154. contentType := h.ContentType()
  2155. if len(contentType) > 0 {
  2156. dst = appendHeaderLine(dst, strContentType, contentType)
  2157. }
  2158. }
  2159. contentEncoding := h.ContentEncoding()
  2160. if len(contentEncoding) > 0 {
  2161. dst = appendHeaderLine(dst, strContentEncoding, contentEncoding)
  2162. }
  2163. if len(h.contentLengthBytes) > 0 {
  2164. dst = appendHeaderLine(dst, strContentLength, h.contentLengthBytes)
  2165. }
  2166. for i, n := 0, len(h.h); i < n; i++ {
  2167. kv := &h.h[i]
  2168. // Exclude trailer from header
  2169. exclude := false
  2170. for _, t := range h.trailer {
  2171. if bytes.Equal(kv.key, t) {
  2172. exclude = true
  2173. break
  2174. }
  2175. }
  2176. if !exclude && (h.noDefaultDate || !bytes.Equal(kv.key, strDate)) {
  2177. dst = appendHeaderLine(dst, kv.key, kv.value)
  2178. }
  2179. }
  2180. if len(h.trailer) > 0 {
  2181. dst = appendHeaderLine(dst, strTrailer, appendTrailerBytes(nil, h.trailer, strCommaSpace))
  2182. }
  2183. n := len(h.cookies)
  2184. if n > 0 {
  2185. for i := 0; i < n; i++ {
  2186. kv := &h.cookies[i]
  2187. dst = appendHeaderLine(dst, strSetCookie, kv.value)
  2188. }
  2189. }
  2190. if h.ConnectionClose() {
  2191. dst = appendHeaderLine(dst, strConnection, strClose)
  2192. }
  2193. return append(dst, strCRLF...)
  2194. }
  2195. // Write writes request header to w.
  2196. func (h *RequestHeader) Write(w *bufio.Writer) error {
  2197. _, err := w.Write(h.Header())
  2198. return err
  2199. }
  2200. // WriteTo writes request header to w.
  2201. //
  2202. // WriteTo implements io.WriterTo interface.
  2203. func (h *RequestHeader) WriteTo(w io.Writer) (int64, error) {
  2204. n, err := w.Write(h.Header())
  2205. return int64(n), err
  2206. }
  2207. // Header returns request header representation.
  2208. //
  2209. // Headers that set as Trailer will not represent. Use TrailerHeader for trailers.
  2210. //
  2211. // The returned value is valid until the request is released,
  2212. // either though ReleaseRequest or your request handler returning.
  2213. // Do not store references to returned value. Make copies instead.
  2214. func (h *RequestHeader) Header() []byte {
  2215. h.bufV = h.AppendBytes(h.bufV[:0])
  2216. return h.bufV
  2217. }
  2218. // writeTrailer writes request trailer to w.
  2219. func (h *RequestHeader) writeTrailer(w *bufio.Writer) error {
  2220. _, err := w.Write(h.TrailerHeader())
  2221. return err
  2222. }
  2223. // TrailerHeader returns request trailer header representation.
  2224. //
  2225. // Trailers will only be received with chunked transfer.
  2226. //
  2227. // The returned value is valid until the request is released,
  2228. // either though ReleaseRequest or your request handler returning.
  2229. // Do not store references to returned value. Make copies instead.
  2230. func (h *RequestHeader) TrailerHeader() []byte {
  2231. h.bufV = h.bufV[:0]
  2232. for _, t := range h.trailer {
  2233. value := h.peek(t)
  2234. h.bufV = appendHeaderLine(h.bufV, t, value)
  2235. }
  2236. h.bufV = append(h.bufV, strCRLF...)
  2237. return h.bufV
  2238. }
  2239. // RawHeaders returns raw header key/value bytes.
  2240. //
  2241. // Depending on server configuration, header keys may be normalized to
  2242. // capital-case in place.
  2243. //
  2244. // This copy is set aside during parsing, so empty slice is returned for all
  2245. // cases where parsing did not happen. Similarly, request line is not stored
  2246. // during parsing and can not be returned.
  2247. //
  2248. // The slice is not safe to use after the handler returns.
  2249. func (h *RequestHeader) RawHeaders() []byte {
  2250. return h.rawHeaders
  2251. }
  2252. // String returns request header representation.
  2253. func (h *RequestHeader) String() string {
  2254. return string(h.Header())
  2255. }
  2256. // AppendBytes appends request header representation to dst and returns
  2257. // the extended dst.
  2258. func (h *RequestHeader) AppendBytes(dst []byte) []byte {
  2259. dst = append(dst, h.Method()...)
  2260. dst = append(dst, ' ')
  2261. dst = append(dst, h.RequestURI()...)
  2262. dst = append(dst, ' ')
  2263. dst = append(dst, h.Protocol()...)
  2264. dst = append(dst, strCRLF...)
  2265. userAgent := h.UserAgent()
  2266. if len(userAgent) > 0 && !h.disableSpecialHeader {
  2267. dst = appendHeaderLine(dst, strUserAgent, userAgent)
  2268. }
  2269. host := h.Host()
  2270. if len(host) > 0 && !h.disableSpecialHeader {
  2271. dst = appendHeaderLine(dst, strHost, host)
  2272. }
  2273. contentType := h.ContentType()
  2274. if !h.noDefaultContentType && len(contentType) == 0 && !h.ignoreBody() {
  2275. contentType = strDefaultContentType
  2276. }
  2277. if len(contentType) > 0 && !h.disableSpecialHeader {
  2278. dst = appendHeaderLine(dst, strContentType, contentType)
  2279. }
  2280. if len(h.contentLengthBytes) > 0 && !h.disableSpecialHeader {
  2281. dst = appendHeaderLine(dst, strContentLength, h.contentLengthBytes)
  2282. }
  2283. for i, n := 0, len(h.h); i < n; i++ {
  2284. kv := &h.h[i]
  2285. // Exclude trailer from header
  2286. exclude := false
  2287. for _, t := range h.trailer {
  2288. if bytes.Equal(kv.key, t) {
  2289. exclude = true
  2290. break
  2291. }
  2292. }
  2293. if !exclude {
  2294. dst = appendHeaderLine(dst, kv.key, kv.value)
  2295. }
  2296. }
  2297. if len(h.trailer) > 0 {
  2298. dst = appendHeaderLine(dst, strTrailer, appendTrailerBytes(nil, h.trailer, strCommaSpace))
  2299. }
  2300. // there is no need in h.collectCookies() here, since if cookies aren't collected yet,
  2301. // they all are located in h.h.
  2302. n := len(h.cookies)
  2303. if n > 0 && !h.disableSpecialHeader {
  2304. dst = append(dst, strCookie...)
  2305. dst = append(dst, strColonSpace...)
  2306. dst = appendRequestCookieBytes(dst, h.cookies)
  2307. dst = append(dst, strCRLF...)
  2308. }
  2309. if h.ConnectionClose() && !h.disableSpecialHeader {
  2310. dst = appendHeaderLine(dst, strConnection, strClose)
  2311. }
  2312. return append(dst, strCRLF...)
  2313. }
  2314. func appendHeaderLine(dst, key, value []byte) []byte {
  2315. dst = append(dst, key...)
  2316. dst = append(dst, strColonSpace...)
  2317. dst = append(dst, value...)
  2318. return append(dst, strCRLF...)
  2319. }
  2320. func (h *ResponseHeader) parse(buf []byte) (int, error) {
  2321. m, err := h.parseFirstLine(buf)
  2322. if err != nil {
  2323. return 0, err
  2324. }
  2325. n, err := h.parseHeaders(buf[m:])
  2326. if err != nil {
  2327. return 0, err
  2328. }
  2329. return m + n, nil
  2330. }
  2331. func (h *RequestHeader) ignoreBody() bool {
  2332. return h.IsGet() || h.IsHead()
  2333. }
  2334. func (h *RequestHeader) parse(buf []byte) (int, error) {
  2335. m, err := h.parseFirstLine(buf)
  2336. if err != nil {
  2337. return 0, err
  2338. }
  2339. h.rawHeaders, _, err = readRawHeaders(h.rawHeaders[:0], buf[m:])
  2340. if err != nil {
  2341. return 0, err
  2342. }
  2343. var n int
  2344. n, err = h.parseHeaders(buf[m:])
  2345. if err != nil {
  2346. return 0, err
  2347. }
  2348. return m + n, nil
  2349. }
  2350. func parseTrailer(src []byte, dest []argsKV, disableNormalizing bool) ([]argsKV, int, error) {
  2351. // Skip any 0 length chunk.
  2352. if src[0] == '0' {
  2353. skip := len(strCRLF) + 1
  2354. if len(src) < skip {
  2355. return dest, 0, io.EOF
  2356. }
  2357. src = src[skip:]
  2358. }
  2359. var s headerScanner
  2360. s.b = src
  2361. for s.next() {
  2362. if len(s.key) == 0 {
  2363. continue
  2364. }
  2365. disable := disableNormalizing
  2366. for _, ch := range s.key {
  2367. if !validHeaderFieldByte(ch) {
  2368. // We accept invalid headers with a space before the
  2369. // colon, but must not canonicalize them.
  2370. // See: https://github.com/valyala/fasthttp/issues/1917
  2371. if ch == ' ' {
  2372. disable = true
  2373. continue
  2374. }
  2375. return dest, 0, fmt.Errorf("invalid trailer key %q", s.key)
  2376. }
  2377. }
  2378. // Forbidden by RFC 7230, section 4.1.2
  2379. if isBadTrailer(s.key) {
  2380. return dest, 0, fmt.Errorf("forbidden trailer key %q", s.key)
  2381. }
  2382. normalizeHeaderKey(s.key, disable)
  2383. dest = appendArgBytes(dest, s.key, s.value, argsHasValue)
  2384. }
  2385. if s.err != nil {
  2386. return dest, 0, s.err
  2387. }
  2388. return dest, s.r, nil
  2389. }
  2390. func isBadTrailer(key []byte) bool {
  2391. if len(key) == 0 {
  2392. return true
  2393. }
  2394. switch key[0] | 0x20 {
  2395. case 'a':
  2396. return caseInsensitiveCompare(key, strAuthorization)
  2397. case 'c':
  2398. // Security fix: Changed > to >= to properly block Content-Type header in trailers
  2399. if len(key) >= len(HeaderContentType) && caseInsensitiveCompare(key[:8], strContentType[:8]) {
  2400. // skip compare prefix 'Content-'
  2401. return caseInsensitiveCompare(key[8:], strContentEncoding[8:]) ||
  2402. caseInsensitiveCompare(key[8:], strContentLength[8:]) ||
  2403. caseInsensitiveCompare(key[8:], strContentType[8:]) ||
  2404. caseInsensitiveCompare(key[8:], strContentRange[8:])
  2405. }
  2406. return caseInsensitiveCompare(key, strConnection) ||
  2407. // Security: Block Cookie header in trailers to prevent session hijacking
  2408. caseInsensitiveCompare(key, strCookie)
  2409. case 'e':
  2410. return caseInsensitiveCompare(key, strExpect)
  2411. case 'h':
  2412. return caseInsensitiveCompare(key, strHost)
  2413. case 'k':
  2414. return caseInsensitiveCompare(key, strKeepAlive)
  2415. case 'l':
  2416. // Security: Block Location header in trailers to prevent redirect attacks
  2417. return caseInsensitiveCompare(key, strLocation)
  2418. case 'm':
  2419. return caseInsensitiveCompare(key, strMaxForwards)
  2420. case 'p':
  2421. if len(key) >= len(HeaderProxyConnection) && caseInsensitiveCompare(key[:6], strProxyConnection[:6]) {
  2422. // skip compare prefix 'Proxy-'
  2423. return caseInsensitiveCompare(key[6:], strProxyConnection[6:]) ||
  2424. caseInsensitiveCompare(key[6:], strProxyAuthenticate[6:]) ||
  2425. caseInsensitiveCompare(key[6:], strProxyAuthorization[6:])
  2426. }
  2427. case 'r':
  2428. return caseInsensitiveCompare(key, strRange)
  2429. case 's':
  2430. // Security: Block Set-Cookie header in trailers
  2431. return caseInsensitiveCompare(key, strSetCookie)
  2432. case 't':
  2433. return caseInsensitiveCompare(key, strTE) ||
  2434. caseInsensitiveCompare(key, strTrailer) ||
  2435. caseInsensitiveCompare(key, strTransferEncoding)
  2436. case 'w':
  2437. return caseInsensitiveCompare(key, strWWWAuthenticate)
  2438. case 'x':
  2439. // Security: Block X-Forwarded-* and X-Real-IP headers to prevent IP spoofing
  2440. return (len(key) >= 11 && caseInsensitiveCompare(key[:11], []byte("x-forwarded"))) ||
  2441. (len(key) >= 9 && caseInsensitiveCompare(key[:9], []byte("x-real-ip")))
  2442. }
  2443. return false
  2444. }
  2445. func (h *ResponseHeader) parseFirstLine(buf []byte) (int, error) {
  2446. bNext := buf
  2447. var b []byte
  2448. var err error
  2449. for len(b) == 0 {
  2450. if b, bNext, err = nextLine(bNext); err != nil {
  2451. return 0, err
  2452. }
  2453. }
  2454. // parse protocol
  2455. n := bytes.IndexByte(b, ' ')
  2456. if n < 0 {
  2457. if h.secureErrorLogMessage {
  2458. return 0, errors.New("cannot find whitespace in the first line of response")
  2459. }
  2460. return 0, fmt.Errorf("cannot find whitespace in the first line of response %q", buf)
  2461. }
  2462. h.noHTTP11 = !bytes.Equal(b[:n], strHTTP11)
  2463. b = b[n+1:]
  2464. // parse status code
  2465. h.statusCode, n, err = parseUintBuf(b)
  2466. if err != nil {
  2467. if h.secureErrorLogMessage {
  2468. return 0, fmt.Errorf("cannot parse response status code: %w", err)
  2469. }
  2470. return 0, fmt.Errorf("cannot parse response status code: %w. Response %q", err, buf)
  2471. }
  2472. if len(b) > n && b[n] != ' ' {
  2473. if h.secureErrorLogMessage {
  2474. return 0, errors.New("unexpected char at the end of status code")
  2475. }
  2476. return 0, fmt.Errorf("unexpected char at the end of status code. Response %q", buf)
  2477. }
  2478. if len(b) > n+1 {
  2479. h.SetStatusMessage(b[n+1:])
  2480. }
  2481. return len(buf) - len(bNext), nil
  2482. }
  2483. func isValidMethod(method []byte) bool {
  2484. for _, ch := range method {
  2485. if validMethodValueByteTable[ch] == 0 {
  2486. return false
  2487. }
  2488. }
  2489. return true
  2490. }
  2491. func (h *RequestHeader) parseFirstLine(buf []byte) (int, error) {
  2492. bNext := buf
  2493. var b []byte
  2494. var err error
  2495. for len(b) == 0 {
  2496. if b, bNext, err = nextLine(bNext); err != nil {
  2497. return 0, err
  2498. }
  2499. }
  2500. // parse method
  2501. n := bytes.IndexByte(b, ' ')
  2502. if n <= 0 {
  2503. if h.secureErrorLogMessage {
  2504. return 0, errors.New("cannot find http request method")
  2505. }
  2506. return 0, fmt.Errorf("cannot find http request method in %q", buf)
  2507. }
  2508. h.method = append(h.method[:0], b[:n]...)
  2509. if !isValidMethod(h.method) {
  2510. if h.secureErrorLogMessage {
  2511. return 0, errors.New("unsupported http request method")
  2512. }
  2513. return 0, fmt.Errorf("unsupported http request method %q in %q", h.method, buf)
  2514. }
  2515. b = b[n+1:]
  2516. // parse requestURI
  2517. n = bytes.LastIndexByte(b, ' ')
  2518. if n < 0 {
  2519. return 0, fmt.Errorf("cannot find whitespace in the first line of request %q", buf)
  2520. } else if n == 0 {
  2521. if h.secureErrorLogMessage {
  2522. return 0, errors.New("requestURI cannot be empty")
  2523. }
  2524. return 0, fmt.Errorf("requestURI cannot be empty in %q", buf)
  2525. }
  2526. protoStr := b[n+1:]
  2527. // Follow RFCs 7230 and 9112 and require that HTTP versions match the following pattern: HTTP/[0-9]\.[0-9]
  2528. if len(protoStr) != len(strHTTP11) {
  2529. if h.secureErrorLogMessage {
  2530. return 0, fmt.Errorf("unsupported HTTP version %q", protoStr)
  2531. }
  2532. return 0, fmt.Errorf("unsupported HTTP version %q in %q", protoStr, buf)
  2533. }
  2534. if !bytes.HasPrefix(protoStr, strHTTP11[:5]) {
  2535. if h.secureErrorLogMessage {
  2536. return 0, fmt.Errorf("unsupported HTTP version %q", protoStr)
  2537. }
  2538. return 0, fmt.Errorf("unsupported HTTP version %q in %q", protoStr, buf)
  2539. }
  2540. if protoStr[5] < '0' || protoStr[5] > '9' || protoStr[7] < '0' || protoStr[7] > '9' {
  2541. if h.secureErrorLogMessage {
  2542. return 0, fmt.Errorf("unsupported HTTP version %q", protoStr)
  2543. }
  2544. return 0, fmt.Errorf("unsupported HTTP version %q in %q", protoStr, buf)
  2545. }
  2546. h.noHTTP11 = !bytes.Equal(protoStr, strHTTP11)
  2547. h.protocol = append(h.protocol[:0], protoStr...)
  2548. h.requestURI = append(h.requestURI[:0], b[:n]...)
  2549. return len(buf) - len(bNext), nil
  2550. }
  2551. func readRawHeaders(dst, buf []byte) ([]byte, int, error) {
  2552. n := bytes.IndexByte(buf, nChar)
  2553. if n < 0 {
  2554. return dst[:0], 0, errNeedMore
  2555. }
  2556. if (n == 1 && buf[0] == rChar) || n == 0 {
  2557. // empty headers
  2558. return dst, n + 1, nil
  2559. }
  2560. n++
  2561. b := buf
  2562. m := n
  2563. for {
  2564. b = b[m:]
  2565. m = bytes.IndexByte(b, nChar)
  2566. if m < 0 {
  2567. return dst, 0, errNeedMore
  2568. }
  2569. m++
  2570. n += m
  2571. if (m == 2 && b[0] == rChar) || m == 1 {
  2572. dst = append(dst, buf[:n]...)
  2573. return dst, n, nil
  2574. }
  2575. }
  2576. }
  2577. func (h *ResponseHeader) parseHeaders(buf []byte) (int, error) {
  2578. // 'identity' content-length by default
  2579. h.contentLength = -2
  2580. var s headerScanner
  2581. s.b = buf
  2582. var kv *argsKV
  2583. for s.next() {
  2584. if len(s.key) == 0 {
  2585. h.connectionClose = true
  2586. return 0, fmt.Errorf("invalid header key %q", s.key)
  2587. }
  2588. disableNormalizing := h.disableNormalizing
  2589. for _, ch := range s.key {
  2590. if !validHeaderFieldByte(ch) {
  2591. h.connectionClose = true
  2592. // We accept invalid headers with a space before the
  2593. // colon, but must not canonicalize them.
  2594. // See: https://github.com/valyala/fasthttp/issues/1917
  2595. if ch == ' ' {
  2596. disableNormalizing = true
  2597. continue
  2598. }
  2599. return 0, fmt.Errorf("invalid header key %q", s.key)
  2600. }
  2601. }
  2602. normalizeHeaderKey(s.key, disableNormalizing)
  2603. for _, ch := range s.value {
  2604. if !validHeaderValueByte(ch) {
  2605. h.connectionClose = true
  2606. return 0, fmt.Errorf("invalid header value %q", s.value)
  2607. }
  2608. }
  2609. switch s.key[0] | 0x20 {
  2610. case 'c':
  2611. if caseInsensitiveCompare(s.key, strContentType) {
  2612. h.contentType = append(h.contentType[:0], s.value...)
  2613. continue
  2614. }
  2615. if caseInsensitiveCompare(s.key, strContentEncoding) {
  2616. h.contentEncoding = append(h.contentEncoding[:0], s.value...)
  2617. continue
  2618. }
  2619. if caseInsensitiveCompare(s.key, strContentLength) {
  2620. if h.contentLength != -1 {
  2621. var err error
  2622. h.contentLength, err = parseContentLength(s.value)
  2623. if err != nil {
  2624. h.contentLength = -2
  2625. h.connectionClose = true
  2626. return 0, err
  2627. }
  2628. h.contentLengthBytes = append(h.contentLengthBytes[:0], s.value...)
  2629. }
  2630. continue
  2631. }
  2632. if caseInsensitiveCompare(s.key, strConnection) {
  2633. if bytes.Equal(s.value, strClose) {
  2634. h.connectionClose = true
  2635. } else {
  2636. h.connectionClose = false
  2637. h.h = appendArgBytes(h.h, s.key, s.value, argsHasValue)
  2638. }
  2639. continue
  2640. }
  2641. case 's':
  2642. if caseInsensitiveCompare(s.key, strServer) {
  2643. h.server = append(h.server[:0], s.value...)
  2644. continue
  2645. }
  2646. if caseInsensitiveCompare(s.key, strSetCookie) {
  2647. h.cookies, kv = allocArg(h.cookies)
  2648. kv.key = getCookieKey(kv.key, s.value)
  2649. kv.value = append(kv.value[:0], s.value...)
  2650. continue
  2651. }
  2652. case 't':
  2653. if caseInsensitiveCompare(s.key, strTransferEncoding) {
  2654. if len(s.value) > 0 && !bytes.Equal(s.value, strIdentity) {
  2655. h.contentLength = -1
  2656. h.h = setArgBytes(h.h, strTransferEncoding, strChunked, argsHasValue)
  2657. }
  2658. continue
  2659. }
  2660. if caseInsensitiveCompare(s.key, strTrailer) {
  2661. err := h.SetTrailerBytes(s.value)
  2662. if err != nil {
  2663. h.connectionClose = true
  2664. return 0, err
  2665. }
  2666. continue
  2667. }
  2668. }
  2669. h.h = appendArgBytes(h.h, s.key, s.value, argsHasValue)
  2670. }
  2671. if s.err != nil {
  2672. h.connectionClose = true
  2673. return 0, s.err
  2674. }
  2675. if h.contentLength < 0 {
  2676. h.contentLengthBytes = h.contentLengthBytes[:0]
  2677. }
  2678. if h.contentLength == -2 && !h.ConnectionUpgrade() && !h.mustSkipContentLength() {
  2679. // According to modern HTTP/1.1 specifications (RFC 7230):
  2680. // `identity` as a value for `Transfer-Encoding` was removed
  2681. // in the errata to RFC 2616.
  2682. // Therefore, we do not include `Transfer-Encoding: identity` in the header.
  2683. // See: https://github.com/valyala/fasthttp/issues/1909
  2684. h.connectionClose = true
  2685. }
  2686. if h.noHTTP11 && !h.connectionClose {
  2687. // close connection for non-http/1.1 response unless 'Connection: keep-alive' is set.
  2688. v := peekArgBytes(h.h, strConnection)
  2689. h.connectionClose = !hasHeaderValue(v, strKeepAlive)
  2690. }
  2691. return s.r, nil
  2692. }
  2693. func (h *RequestHeader) parseHeaders(buf []byte) (int, error) {
  2694. h.contentLength = -2
  2695. contentLengthSeen := false
  2696. var s headerScanner
  2697. s.b = buf
  2698. for s.next() {
  2699. if len(s.key) == 0 {
  2700. h.connectionClose = true
  2701. return 0, fmt.Errorf("invalid header key %q", s.key)
  2702. }
  2703. disableNormalizing := h.disableNormalizing
  2704. for _, ch := range s.key {
  2705. if !validHeaderFieldByte(ch) {
  2706. if ch == ' ' {
  2707. disableNormalizing = true
  2708. continue
  2709. }
  2710. h.connectionClose = true
  2711. return 0, fmt.Errorf("invalid header key %q", s.key)
  2712. }
  2713. }
  2714. normalizeHeaderKey(s.key, disableNormalizing)
  2715. for _, ch := range s.value {
  2716. if !validHeaderValueByte(ch) {
  2717. h.connectionClose = true
  2718. return 0, fmt.Errorf("invalid header value %q", s.value)
  2719. }
  2720. }
  2721. if h.disableSpecialHeader {
  2722. h.h = appendArgBytes(h.h, s.key, s.value, argsHasValue)
  2723. continue
  2724. }
  2725. switch s.key[0] | 0x20 {
  2726. case 'h':
  2727. if caseInsensitiveCompare(s.key, strHost) {
  2728. h.host = append(h.host[:0], s.value...)
  2729. continue
  2730. }
  2731. case 'u':
  2732. if caseInsensitiveCompare(s.key, strUserAgent) {
  2733. h.userAgent = append(h.userAgent[:0], s.value...)
  2734. continue
  2735. }
  2736. case 'c':
  2737. if caseInsensitiveCompare(s.key, strContentType) {
  2738. h.contentType = append(h.contentType[:0], s.value...)
  2739. continue
  2740. }
  2741. if caseInsensitiveCompare(s.key, strContentLength) {
  2742. if contentLengthSeen {
  2743. h.connectionClose = true
  2744. return 0, errors.New("duplicate Content-Length header")
  2745. }
  2746. contentLengthSeen = true
  2747. if h.contentLength != -1 {
  2748. var err error
  2749. h.contentLength, err = parseContentLength(s.value)
  2750. if err != nil {
  2751. h.contentLength = -2
  2752. h.connectionClose = true
  2753. return 0, err
  2754. }
  2755. h.contentLengthBytes = append(h.contentLengthBytes[:0], s.value...)
  2756. }
  2757. continue
  2758. }
  2759. if caseInsensitiveCompare(s.key, strConnection) {
  2760. if bytes.Equal(s.value, strClose) {
  2761. h.connectionClose = true
  2762. } else {
  2763. h.connectionClose = false
  2764. h.h = appendArgBytes(h.h, s.key, s.value, argsHasValue)
  2765. }
  2766. continue
  2767. }
  2768. case 't':
  2769. if caseInsensitiveCompare(s.key, strTransferEncoding) {
  2770. isIdentity := caseInsensitiveCompare(s.value, strIdentity)
  2771. isChunked := caseInsensitiveCompare(s.value, strChunked)
  2772. if !isIdentity && !isChunked {
  2773. h.connectionClose = true
  2774. if h.secureErrorLogMessage {
  2775. return 0, errors.New("unsupported Transfer-Encoding")
  2776. }
  2777. return 0, fmt.Errorf("unsupported Transfer-Encoding: %q", s.value)
  2778. }
  2779. if isChunked {
  2780. h.contentLength = -1
  2781. h.h = setArgBytes(h.h, strTransferEncoding, strChunked, argsHasValue)
  2782. }
  2783. continue
  2784. }
  2785. if caseInsensitiveCompare(s.key, strTrailer) {
  2786. err := h.SetTrailerBytes(s.value)
  2787. if err != nil {
  2788. h.connectionClose = true
  2789. return 0, err
  2790. }
  2791. continue
  2792. }
  2793. }
  2794. h.h = appendArgBytes(h.h, s.key, s.value, argsHasValue)
  2795. }
  2796. if s.err != nil {
  2797. h.connectionClose = true
  2798. return 0, s.err
  2799. }
  2800. if h.contentLength < 0 {
  2801. h.contentLengthBytes = h.contentLengthBytes[:0]
  2802. }
  2803. if h.noHTTP11 && !h.connectionClose {
  2804. // close connection for non-http/1.1 request unless 'Connection: keep-alive' is set.
  2805. v := peekArgBytes(h.h, strConnection)
  2806. h.connectionClose = !hasHeaderValue(v, strKeepAlive)
  2807. }
  2808. return s.r, nil
  2809. }
  2810. func (h *RequestHeader) collectCookies() {
  2811. if h.cookiesCollected {
  2812. return
  2813. }
  2814. for i, n := 0, len(h.h); i < n; i++ {
  2815. kv := &h.h[i]
  2816. if caseInsensitiveCompare(kv.key, strCookie) {
  2817. h.cookies = parseRequestCookies(h.cookies, kv.value)
  2818. tmp := *kv
  2819. copy(h.h[i:], h.h[i+1:])
  2820. n--
  2821. i--
  2822. h.h[n] = tmp
  2823. h.h = h.h[:n]
  2824. }
  2825. }
  2826. h.cookiesCollected = true
  2827. }
  2828. var errNonNumericChars = errors.New("non-numeric chars found")
  2829. func parseContentLength(b []byte) (int, error) {
  2830. v, n, err := parseUintBuf(b)
  2831. if err != nil {
  2832. return -1, fmt.Errorf("cannot parse Content-Length: %w", err)
  2833. }
  2834. if n != len(b) {
  2835. return -1, fmt.Errorf("cannot parse Content-Length: %w", errNonNumericChars)
  2836. }
  2837. return v, nil
  2838. }
  2839. type headerValueScanner struct {
  2840. b []byte
  2841. value []byte
  2842. }
  2843. func (s *headerValueScanner) next() bool {
  2844. b := s.b
  2845. if len(b) == 0 {
  2846. return false
  2847. }
  2848. n := bytes.IndexByte(b, ',')
  2849. if n < 0 {
  2850. s.value = stripSpace(b)
  2851. s.b = b[len(b):]
  2852. return true
  2853. }
  2854. s.value = stripSpace(b[:n])
  2855. s.b = b[n+1:]
  2856. return true
  2857. }
  2858. func stripSpace(b []byte) []byte {
  2859. for len(b) > 0 && b[0] == ' ' {
  2860. b = b[1:]
  2861. }
  2862. for len(b) > 0 && b[len(b)-1] == ' ' {
  2863. b = b[:len(b)-1]
  2864. }
  2865. return b
  2866. }
  2867. func hasHeaderValue(s, value []byte) bool {
  2868. var vs headerValueScanner
  2869. vs.b = s
  2870. for vs.next() {
  2871. if caseInsensitiveCompare(vs.value, value) {
  2872. return true
  2873. }
  2874. }
  2875. return false
  2876. }
  2877. func nextLine(b []byte) ([]byte, []byte, error) {
  2878. nNext := bytes.IndexByte(b, nChar)
  2879. if nNext < 0 {
  2880. return nil, nil, errNeedMore
  2881. }
  2882. n := nNext
  2883. if n > 0 && b[n-1] == rChar {
  2884. n--
  2885. }
  2886. return b[:n], b[nNext+1:], nil
  2887. }
  2888. func initHeaderKV(bufK, bufV []byte, key, value string, disableNormalizing bool) ([]byte, []byte) {
  2889. bufK = getHeaderKeyBytes(bufK, key, disableNormalizing)
  2890. // https://tools.ietf.org/html/rfc7230#section-3.2.4
  2891. bufV = append(bufV[:0], value...)
  2892. bufV = removeNewLines(bufV)
  2893. return bufK, bufV
  2894. }
  2895. func getHeaderKeyBytes(bufK []byte, key string, disableNormalizing bool) []byte {
  2896. bufK = append(bufK[:0], key...)
  2897. normalizeHeaderKey(bufK, disableNormalizing || bytes.IndexByte(bufK, ' ') != -1)
  2898. return bufK
  2899. }
  2900. func normalizeHeaderKey(b []byte, disableNormalizing bool) {
  2901. if disableNormalizing {
  2902. return
  2903. }
  2904. n := len(b)
  2905. if n == 0 {
  2906. return
  2907. }
  2908. // If the header isn't valid, we don't normalize it.
  2909. for _, c := range b {
  2910. if !validHeaderFieldByte(c) {
  2911. return
  2912. }
  2913. }
  2914. upper := true
  2915. for i, c := range b {
  2916. if upper {
  2917. c = toUpperTable[c]
  2918. } else {
  2919. c = toLowerTable[c]
  2920. }
  2921. upper = c == '-'
  2922. b[i] = c
  2923. }
  2924. }
  2925. // removeNewLines will replace `\r` and `\n` with an empty space.
  2926. func removeNewLines(raw []byte) []byte {
  2927. // check if a `\r` is present and save the position.
  2928. // if no `\r` is found, check if a `\n` is present.
  2929. foundR := bytes.IndexByte(raw, rChar)
  2930. foundN := bytes.IndexByte(raw, nChar)
  2931. start := 0
  2932. switch {
  2933. case foundN != -1:
  2934. if foundR > foundN {
  2935. start = foundN
  2936. } else if foundR != -1 {
  2937. start = foundR
  2938. }
  2939. case foundR != -1:
  2940. start = foundR
  2941. default:
  2942. return raw
  2943. }
  2944. for i := start; i < len(raw); i++ {
  2945. switch raw[i] {
  2946. case rChar, nChar:
  2947. raw[i] = ' '
  2948. default:
  2949. continue
  2950. }
  2951. }
  2952. return raw
  2953. }
  2954. // AppendNormalizedHeaderKey appends normalized header key (name) to dst
  2955. // and returns the resulting dst.
  2956. //
  2957. // Normalized header key starts with uppercase letter. The first letters
  2958. // after dashes are also uppercased. All the other letters are lowercased.
  2959. // Examples:
  2960. //
  2961. // - coNTENT-TYPe -> Content-Type
  2962. // - HOST -> Host
  2963. // - foo-bar-baz -> Foo-Bar-Baz
  2964. func AppendNormalizedHeaderKey(dst []byte, key string) []byte {
  2965. dst = append(dst, key...)
  2966. normalizeHeaderKey(dst[len(dst)-len(key):], false)
  2967. return dst
  2968. }
  2969. // AppendNormalizedHeaderKeyBytes appends normalized header key (name) to dst
  2970. // and returns the resulting dst.
  2971. //
  2972. // Normalized header key starts with uppercase letter. The first letters
  2973. // after dashes are also uppercased. All the other letters are lowercased.
  2974. // Examples:
  2975. //
  2976. // - coNTENT-TYPe -> Content-Type
  2977. // - HOST -> Host
  2978. // - foo-bar-baz -> Foo-Bar-Baz
  2979. func AppendNormalizedHeaderKeyBytes(dst, key []byte) []byte {
  2980. return AppendNormalizedHeaderKey(dst, b2s(key))
  2981. }
  2982. func appendTrailerBytes(dst []byte, trailer [][]byte, sep []byte) []byte {
  2983. for i, n := 0, len(trailer); i < n; i++ {
  2984. dst = append(dst, trailer[i]...)
  2985. if i+1 < n {
  2986. dst = append(dst, sep...)
  2987. }
  2988. }
  2989. return dst
  2990. }
  2991. func copyTrailer(dst, src [][]byte) [][]byte {
  2992. if cap(dst) > len(src) {
  2993. dst = dst[:len(src)]
  2994. } else {
  2995. dst = append(dst[:0], src...)
  2996. }
  2997. for i := range dst {
  2998. dst[i] = make([]byte, len(src[i]))
  2999. copy(dst[i], src[i])
  3000. }
  3001. return dst
  3002. }
  3003. var (
  3004. errNeedMore = errors.New("need more data: cannot find trailing lf")
  3005. errSmallBuffer = errors.New("small read buffer. Increase ReadBufferSize")
  3006. )
  3007. // ErrNothingRead is returned when a keep-alive connection is closed,
  3008. // either because the remote closed it or because of a read timeout.
  3009. type ErrNothingRead struct {
  3010. error
  3011. }
  3012. // ErrSmallBuffer is returned when the provided buffer size is too small
  3013. // for reading request and/or response headers.
  3014. //
  3015. // ReadBufferSize value from Server or clients should reduce the number
  3016. // of such errors.
  3017. type ErrSmallBuffer struct {
  3018. error
  3019. }
  3020. func mustPeekBuffered(r *bufio.Reader) []byte {
  3021. buf, err := r.Peek(r.Buffered())
  3022. if len(buf) == 0 || err != nil {
  3023. panic(fmt.Sprintf("bufio.Reader.Peek() returned unexpected data (%q, %v)", buf, err))
  3024. }
  3025. return buf
  3026. }
  3027. func mustDiscard(r *bufio.Reader, n int) {
  3028. if _, err := r.Discard(n); err != nil {
  3029. panic(fmt.Sprintf("bufio.Reader.Discard(%d) failed: %v", n, err))
  3030. }
  3031. }