header.go 99 KB

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