header.go 96 KB

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