header.go 95 KB

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