You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

http.py 102KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131
  1. # -*- test-case-name: twisted.web.test.test_http -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. HyperText Transfer Protocol implementation.
  6. This is the basic server-side protocol implementation used by the Twisted
  7. Web server. It can parse HTTP 1.0 requests and supports many HTTP 1.1
  8. features as well. Additionally, some functionality implemented here is
  9. also useful for HTTP clients (such as the chunked encoding parser).
  10. @var CACHED: A marker value to be returned from cache-related request methods
  11. to indicate to the caller that a cached response will be usable and no
  12. response body should be generated.
  13. @var FOUND: An HTTP response code indicating a temporary redirect.
  14. @var NOT_MODIFIED: An HTTP response code indicating that a requested
  15. pre-condition (for example, the condition represented by an
  16. I{If-Modified-Since} header is present in the request) has succeeded. This
  17. indicates a response body cached by the client can be used.
  18. @var PRECONDITION_FAILED: An HTTP response code indicating that a requested
  19. pre-condition (for example, the condition represented by an I{If-None-Match}
  20. header is present in the request) has failed. This should typically
  21. indicate that the server has not taken the requested action.
  22. """
  23. from __future__ import division, absolute_import
  24. __all__ = [
  25. 'SWITCHING', 'OK', 'CREATED', 'ACCEPTED', 'NON_AUTHORITATIVE_INFORMATION',
  26. 'NO_CONTENT', 'RESET_CONTENT', 'PARTIAL_CONTENT', 'MULTI_STATUS',
  27. 'MULTIPLE_CHOICE', 'MOVED_PERMANENTLY', 'FOUND', 'SEE_OTHER',
  28. 'NOT_MODIFIED', 'USE_PROXY', 'TEMPORARY_REDIRECT',
  29. 'BAD_REQUEST', 'UNAUTHORIZED', 'PAYMENT_REQUIRED', 'FORBIDDEN', 'NOT_FOUND',
  30. 'NOT_ALLOWED', 'NOT_ACCEPTABLE', 'PROXY_AUTH_REQUIRED', 'REQUEST_TIMEOUT',
  31. 'CONFLICT', 'GONE', 'LENGTH_REQUIRED', 'PRECONDITION_FAILED',
  32. 'REQUEST_ENTITY_TOO_LARGE', 'REQUEST_URI_TOO_LONG',
  33. 'UNSUPPORTED_MEDIA_TYPE', 'REQUESTED_RANGE_NOT_SATISFIABLE',
  34. 'EXPECTATION_FAILED',
  35. 'INTERNAL_SERVER_ERROR', 'NOT_IMPLEMENTED', 'BAD_GATEWAY',
  36. 'SERVICE_UNAVAILABLE', 'GATEWAY_TIMEOUT', 'HTTP_VERSION_NOT_SUPPORTED',
  37. 'INSUFFICIENT_STORAGE_SPACE', 'NOT_EXTENDED',
  38. 'RESPONSES', 'CACHED',
  39. 'urlparse', 'parse_qs', 'datetimeToString', 'datetimeToLogString', 'timegm',
  40. 'stringToDatetime', 'toChunk', 'fromChunk', 'parseContentRange',
  41. 'StringTransport', 'HTTPClient', 'NO_BODY_CODES', 'Request',
  42. 'PotentialDataLoss', 'HTTPChannel', 'HTTPFactory',
  43. ]
  44. # system imports
  45. import tempfile
  46. import base64, binascii
  47. import cgi
  48. import math
  49. import time
  50. import calendar
  51. import warnings
  52. import os
  53. from io import BytesIO as StringIO
  54. try:
  55. from urlparse import (
  56. ParseResult as ParseResultBytes, urlparse as _urlparse)
  57. from urllib import unquote
  58. from cgi import parse_header as _parseHeader
  59. except ImportError:
  60. from urllib.parse import (
  61. ParseResultBytes, urlparse as _urlparse, unquote_to_bytes as unquote)
  62. def _parseHeader(line):
  63. # cgi.parse_header requires a str
  64. key, pdict = cgi.parse_header(line.decode('charmap'))
  65. # We want the key as bytes, and cgi.parse_multipart (which consumes
  66. # pdict) expects a dict of str keys but bytes values
  67. key = key.encode('charmap')
  68. pdict = {x:y.encode('charmap') for x, y in pdict.items()}
  69. return (key, pdict)
  70. from zope.interface import Attribute, Interface, implementer, provider
  71. # twisted imports
  72. from twisted.python.compat import (
  73. _PY3, long, unicode, intToBytes, networkString, nativeString, _PY37PLUS)
  74. from twisted.python.deprecate import deprecated
  75. from twisted.python import log
  76. from twisted.logger import Logger
  77. from twisted.python.failure import Failure
  78. from incremental import Version
  79. from twisted.python.components import proxyForInterface
  80. from twisted.internet import interfaces, protocol, address
  81. from twisted.internet.defer import Deferred
  82. from twisted.internet.interfaces import IProtocol
  83. from twisted.internet._producer_helpers import _PullToPush
  84. from twisted.protocols import policies, basic
  85. from twisted.web.iweb import (
  86. IRequest, IAccessLogFormatter, INonQueuedRequestFactory)
  87. from twisted.web.http_headers import Headers, _sanitizeLinearWhitespace
  88. try:
  89. from twisted.web._http2 import H2Connection
  90. H2_ENABLED = True
  91. except ImportError:
  92. H2Connection = None
  93. H2_ENABLED = False
  94. from twisted.web._responses import (
  95. SWITCHING,
  96. OK, CREATED, ACCEPTED, NON_AUTHORITATIVE_INFORMATION, NO_CONTENT,
  97. RESET_CONTENT, PARTIAL_CONTENT, MULTI_STATUS,
  98. MULTIPLE_CHOICE, MOVED_PERMANENTLY, FOUND, SEE_OTHER, NOT_MODIFIED,
  99. USE_PROXY, TEMPORARY_REDIRECT,
  100. BAD_REQUEST, UNAUTHORIZED, PAYMENT_REQUIRED, FORBIDDEN, NOT_FOUND,
  101. NOT_ALLOWED, NOT_ACCEPTABLE, PROXY_AUTH_REQUIRED, REQUEST_TIMEOUT,
  102. CONFLICT, GONE, LENGTH_REQUIRED, PRECONDITION_FAILED,
  103. REQUEST_ENTITY_TOO_LARGE, REQUEST_URI_TOO_LONG, UNSUPPORTED_MEDIA_TYPE,
  104. REQUESTED_RANGE_NOT_SATISFIABLE, EXPECTATION_FAILED,
  105. INTERNAL_SERVER_ERROR, NOT_IMPLEMENTED, BAD_GATEWAY, SERVICE_UNAVAILABLE,
  106. GATEWAY_TIMEOUT, HTTP_VERSION_NOT_SUPPORTED, INSUFFICIENT_STORAGE_SPACE,
  107. NOT_EXTENDED,
  108. RESPONSES)
  109. _intTypes = (int, long)
  110. # A common request timeout -- 1 minute. This is roughly what nginx uses, and
  111. # so it seems to be a good choice for us too.
  112. _REQUEST_TIMEOUT = 1 * 60
  113. protocol_version = "HTTP/1.1"
  114. CACHED = """Magic constant returned by http.Request methods to set cache
  115. validation headers when the request is conditional and the value fails
  116. the condition."""
  117. # backwards compatibility
  118. responses = RESPONSES
  119. # datetime parsing and formatting
  120. weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  121. monthname = [None,
  122. 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  123. 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  124. weekdayname_lower = [name.lower() for name in weekdayname]
  125. monthname_lower = [name and name.lower() for name in monthname]
  126. def urlparse(url):
  127. """
  128. Parse an URL into six components.
  129. This is similar to C{urlparse.urlparse}, but rejects C{unicode} input
  130. and always produces C{bytes} output.
  131. @type url: C{bytes}
  132. @raise TypeError: The given url was a C{unicode} string instead of a
  133. C{bytes}.
  134. @return: The scheme, net location, path, params, query string, and fragment
  135. of the URL - all as C{bytes}.
  136. @rtype: C{ParseResultBytes}
  137. """
  138. if isinstance(url, unicode):
  139. raise TypeError("url must be bytes, not unicode")
  140. scheme, netloc, path, params, query, fragment = _urlparse(url)
  141. if isinstance(scheme, unicode):
  142. scheme = scheme.encode('ascii')
  143. netloc = netloc.encode('ascii')
  144. path = path.encode('ascii')
  145. query = query.encode('ascii')
  146. fragment = fragment.encode('ascii')
  147. return ParseResultBytes(scheme, netloc, path, params, query, fragment)
  148. def parse_qs(qs, keep_blank_values=0, strict_parsing=0):
  149. """
  150. Like C{cgi.parse_qs}, but with support for parsing byte strings on Python 3.
  151. @type qs: C{bytes}
  152. """
  153. d = {}
  154. items = [s2 for s1 in qs.split(b"&") for s2 in s1.split(b";")]
  155. for item in items:
  156. try:
  157. k, v = item.split(b"=", 1)
  158. except ValueError:
  159. if strict_parsing:
  160. raise
  161. continue
  162. if v or keep_blank_values:
  163. k = unquote(k.replace(b"+", b" "))
  164. v = unquote(v.replace(b"+", b" "))
  165. if k in d:
  166. d[k].append(v)
  167. else:
  168. d[k] = [v]
  169. return d
  170. def datetimeToString(msSinceEpoch=None):
  171. """
  172. Convert seconds since epoch to HTTP datetime string.
  173. @rtype: C{bytes}
  174. """
  175. if msSinceEpoch == None:
  176. msSinceEpoch = time.time()
  177. year, month, day, hh, mm, ss, wd, y, z = time.gmtime(msSinceEpoch)
  178. s = networkString("%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
  179. weekdayname[wd],
  180. day, monthname[month], year,
  181. hh, mm, ss))
  182. return s
  183. def datetimeToLogString(msSinceEpoch=None):
  184. """
  185. Convert seconds since epoch to log datetime string.
  186. @rtype: C{str}
  187. """
  188. if msSinceEpoch == None:
  189. msSinceEpoch = time.time()
  190. year, month, day, hh, mm, ss, wd, y, z = time.gmtime(msSinceEpoch)
  191. s = "[%02d/%3s/%4d:%02d:%02d:%02d +0000]" % (
  192. day, monthname[month], year,
  193. hh, mm, ss)
  194. return s
  195. def timegm(year, month, day, hour, minute, second):
  196. """
  197. Convert time tuple in GMT to seconds since epoch, GMT
  198. """
  199. EPOCH = 1970
  200. if year < EPOCH:
  201. raise ValueError("Years prior to %d not supported" % (EPOCH,))
  202. assert 1 <= month <= 12
  203. days = 365*(year-EPOCH) + calendar.leapdays(EPOCH, year)
  204. for i in range(1, month):
  205. days = days + calendar.mdays[i]
  206. if month > 2 and calendar.isleap(year):
  207. days = days + 1
  208. days = days + day - 1
  209. hours = days*24 + hour
  210. minutes = hours*60 + minute
  211. seconds = minutes*60 + second
  212. return seconds
  213. def stringToDatetime(dateString):
  214. """
  215. Convert an HTTP date string (one of three formats) to seconds since epoch.
  216. @type dateString: C{bytes}
  217. """
  218. parts = nativeString(dateString).split()
  219. if not parts[0][0:3].lower() in weekdayname_lower:
  220. # Weekday is stupid. Might have been omitted.
  221. try:
  222. return stringToDatetime(b"Sun, " + dateString)
  223. except ValueError:
  224. # Guess not.
  225. pass
  226. partlen = len(parts)
  227. if (partlen == 5 or partlen == 6) and parts[1].isdigit():
  228. # 1st date format: Sun, 06 Nov 1994 08:49:37 GMT
  229. # (Note: "GMT" is literal, not a variable timezone)
  230. # (also handles without "GMT")
  231. # This is the normal format
  232. day = parts[1]
  233. month = parts[2]
  234. year = parts[3]
  235. time = parts[4]
  236. elif (partlen == 3 or partlen == 4) and parts[1].find('-') != -1:
  237. # 2nd date format: Sunday, 06-Nov-94 08:49:37 GMT
  238. # (Note: "GMT" is literal, not a variable timezone)
  239. # (also handles without without "GMT")
  240. # Two digit year, yucko.
  241. day, month, year = parts[1].split('-')
  242. time = parts[2]
  243. year=int(year)
  244. if year < 69:
  245. year = year + 2000
  246. elif year < 100:
  247. year = year + 1900
  248. elif len(parts) == 5:
  249. # 3rd date format: Sun Nov 6 08:49:37 1994
  250. # ANSI C asctime() format.
  251. day = parts[2]
  252. month = parts[1]
  253. year = parts[4]
  254. time = parts[3]
  255. else:
  256. raise ValueError("Unknown datetime format %r" % dateString)
  257. day = int(day)
  258. month = int(monthname_lower.index(month.lower()))
  259. year = int(year)
  260. hour, min, sec = map(int, time.split(':'))
  261. return int(timegm(year, month, day, hour, min, sec))
  262. def toChunk(data):
  263. """
  264. Convert string to a chunk.
  265. @type data: C{bytes}
  266. @returns: a tuple of C{bytes} representing the chunked encoding of data
  267. """
  268. return (networkString('%x' % (len(data),)), b"\r\n", data, b"\r\n")
  269. def fromChunk(data):
  270. """
  271. Convert chunk to string.
  272. @type data: C{bytes}
  273. @return: tuple of (result, remaining) - both C{bytes}.
  274. @raise ValueError: If the given data is not a correctly formatted chunked
  275. byte string.
  276. """
  277. prefix, rest = data.split(b'\r\n', 1)
  278. length = int(prefix, 16)
  279. if length < 0:
  280. raise ValueError("Chunk length must be >= 0, not %d" % (length,))
  281. if rest[length:length + 2] != b'\r\n':
  282. raise ValueError("chunk must end with CRLF")
  283. return rest[:length], rest[length + 2:]
  284. def parseContentRange(header):
  285. """
  286. Parse a content-range header into (start, end, realLength).
  287. realLength might be None if real length is not known ('*').
  288. """
  289. kind, other = header.strip().split()
  290. if kind.lower() != "bytes":
  291. raise ValueError("a range of type %r is not supported")
  292. startend, realLength = other.split("/")
  293. start, end = map(int, startend.split("-"))
  294. if realLength == "*":
  295. realLength = None
  296. else:
  297. realLength = int(realLength)
  298. return (start, end, realLength)
  299. class _IDeprecatedHTTPChannelToRequestInterface(Interface):
  300. """
  301. The interface L{HTTPChannel} expects of L{Request}.
  302. """
  303. requestHeaders = Attribute(
  304. "A L{http_headers.Headers} instance giving all received HTTP request "
  305. "headers.")
  306. responseHeaders = Attribute(
  307. "A L{http_headers.Headers} instance holding all HTTP response "
  308. "headers to be sent.")
  309. def connectionLost(reason):
  310. """
  311. The underlying connection has been lost.
  312. @param reason: A failure instance indicating the reason why
  313. the connection was lost.
  314. @type reason: L{twisted.python.failure.Failure}
  315. """
  316. def gotLength(length):
  317. """
  318. Called when L{HTTPChannel} has determined the length, if any,
  319. of the incoming request's body.
  320. @param length: The length of the request's body.
  321. @type length: L{int} if the request declares its body's length
  322. and L{None} if it does not.
  323. """
  324. def handleContentChunk(data):
  325. """
  326. Deliver a received chunk of body data to the request. Note
  327. this does not imply chunked transfer encoding.
  328. @param data: The received chunk.
  329. @type data: L{bytes}
  330. """
  331. def parseCookies():
  332. """
  333. Parse the request's cookies out of received headers.
  334. """
  335. def requestReceived(command, path, version):
  336. """
  337. Called when the entire request, including its body, has been
  338. received.
  339. @param command: The request's HTTP command.
  340. @type command: L{bytes}
  341. @param path: The request's path. Note: this is actually what
  342. RFC7320 calls the URI.
  343. @type path: L{bytes}
  344. @param version: The request's HTTP version.
  345. @type version: L{bytes}
  346. """
  347. def __eq__(other):
  348. """
  349. Determines if two requests are the same object.
  350. @param other: Another object whose identity will be compared
  351. to this instance's.
  352. @return: L{True} when the two are the same object and L{False}
  353. when not.
  354. @rtype: L{bool}
  355. """
  356. def __ne__(other):
  357. """
  358. Determines if two requests are not the same object.
  359. @param other: Another object whose identity will be compared
  360. to this instance's.
  361. @return: L{True} when the two are not the same object and
  362. L{False} when they are.
  363. @rtype: L{bool}
  364. """
  365. def __hash__():
  366. """
  367. Generate a hash value for the request.
  368. @return: The request's hash value.
  369. @rtype: L{int}
  370. """
  371. class StringTransport:
  372. """
  373. I am a StringIO wrapper that conforms for the transport API. I support
  374. the `writeSequence' method.
  375. """
  376. def __init__(self):
  377. self.s = StringIO()
  378. def writeSequence(self, seq):
  379. self.s.write(b''.join(seq))
  380. def __getattr__(self, attr):
  381. return getattr(self.__dict__['s'], attr)
  382. class HTTPClient(basic.LineReceiver):
  383. """
  384. A client for HTTP 1.0.
  385. Notes:
  386. You probably want to send a 'Host' header with the name of the site you're
  387. connecting to, in order to not break name based virtual hosting.
  388. @ivar length: The length of the request body in bytes.
  389. @type length: C{int}
  390. @ivar firstLine: Are we waiting for the first header line?
  391. @type firstLine: C{bool}
  392. @ivar __buffer: The buffer that stores the response to the HTTP request.
  393. @type __buffer: A C{StringIO} object.
  394. @ivar _header: Part or all of an HTTP request header.
  395. @type _header: C{bytes}
  396. """
  397. length = None
  398. firstLine = True
  399. __buffer = None
  400. _header = b""
  401. def sendCommand(self, command, path):
  402. self.transport.writeSequence([command, b' ', path, b' HTTP/1.0\r\n'])
  403. def sendHeader(self, name, value):
  404. if not isinstance(value, bytes):
  405. # XXX Deprecate this case
  406. value = networkString(str(value))
  407. santizedName = _sanitizeLinearWhitespace(name)
  408. santizedValue = _sanitizeLinearWhitespace(value)
  409. self.transport.writeSequence(
  410. [santizedName, b': ', santizedValue, b'\r\n'])
  411. def endHeaders(self):
  412. self.transport.write(b'\r\n')
  413. def extractHeader(self, header):
  414. """
  415. Given a complete HTTP header, extract the field name and value and
  416. process the header.
  417. @param header: a complete HTTP request header of the form
  418. 'field-name: value'.
  419. @type header: C{bytes}
  420. """
  421. key, val = header.split(b':', 1)
  422. val = val.lstrip()
  423. self.handleHeader(key, val)
  424. if key.lower() == b'content-length':
  425. self.length = int(val)
  426. def lineReceived(self, line):
  427. """
  428. Parse the status line and headers for an HTTP request.
  429. @param line: Part of an HTTP request header. Request bodies are parsed
  430. in L{HTTPClient.rawDataReceived}.
  431. @type line: C{bytes}
  432. """
  433. if self.firstLine:
  434. self.firstLine = False
  435. l = line.split(None, 2)
  436. version = l[0]
  437. status = l[1]
  438. try:
  439. message = l[2]
  440. except IndexError:
  441. # sometimes there is no message
  442. message = b""
  443. self.handleStatus(version, status, message)
  444. return
  445. if not line:
  446. if self._header != b"":
  447. # Only extract headers if there are any
  448. self.extractHeader(self._header)
  449. self.__buffer = StringIO()
  450. self.handleEndHeaders()
  451. self.setRawMode()
  452. return
  453. if line.startswith(b'\t') or line.startswith(b' '):
  454. # This line is part of a multiline header. According to RFC 822, in
  455. # "unfolding" multiline headers you do not strip the leading
  456. # whitespace on the continuing line.
  457. self._header = self._header + line
  458. elif self._header:
  459. # This line starts a new header, so process the previous one.
  460. self.extractHeader(self._header)
  461. self._header = line
  462. else: # First header
  463. self._header = line
  464. def connectionLost(self, reason):
  465. self.handleResponseEnd()
  466. def handleResponseEnd(self):
  467. """
  468. The response has been completely received.
  469. This callback may be invoked more than once per request.
  470. """
  471. if self.__buffer is not None:
  472. b = self.__buffer.getvalue()
  473. self.__buffer = None
  474. self.handleResponse(b)
  475. def handleResponsePart(self, data):
  476. self.__buffer.write(data)
  477. def connectionMade(self):
  478. pass
  479. def handleStatus(self, version, status, message):
  480. """
  481. Called when the status-line is received.
  482. @param version: e.g. 'HTTP/1.0'
  483. @param status: e.g. '200'
  484. @type status: C{bytes}
  485. @param message: e.g. 'OK'
  486. """
  487. def handleHeader(self, key, val):
  488. """
  489. Called every time a header is received.
  490. """
  491. def handleEndHeaders(self):
  492. """
  493. Called when all headers have been received.
  494. """
  495. def rawDataReceived(self, data):
  496. if self.length is not None:
  497. data, rest = data[:self.length], data[self.length:]
  498. self.length -= len(data)
  499. else:
  500. rest = b''
  501. self.handleResponsePart(data)
  502. if self.length == 0:
  503. self.handleResponseEnd()
  504. self.setLineMode(rest)
  505. # response codes that must have empty bodies
  506. NO_BODY_CODES = (204, 304)
  507. # Sentinel object that detects people explicitly passing `queued` to Request.
  508. _QUEUED_SENTINEL = object()
  509. def _getContentFile(length):
  510. """
  511. Get a writeable file-like object to which request content can be written.
  512. """
  513. if length is not None and length < 100000:
  514. return StringIO()
  515. return tempfile.TemporaryFile()
  516. @implementer(interfaces.IConsumer,
  517. _IDeprecatedHTTPChannelToRequestInterface)
  518. class Request:
  519. """
  520. A HTTP request.
  521. Subclasses should override the process() method to determine how
  522. the request will be processed.
  523. @ivar method: The HTTP method that was used, e.g. C{b'GET'}.
  524. @type method: L{bytes}
  525. @ivar uri: The full encoded URI which was requested (including query
  526. arguments), e.g. C{b'/a/b%20/c?q=v'}.
  527. @type uri: L{bytes}
  528. @ivar path: The encoded path of the request URI (not including query
  529. arguments), e.g. C{b'/a/b%20/c'}.
  530. @type path: L{bytes}
  531. @ivar args: A mapping of decoded query argument names as L{bytes} to
  532. corresponding query argument values as L{list}s of L{bytes}.
  533. For example, for a URI with C{foo=bar&foo=baz&quux=spam}
  534. as its query part C{args} will be C{{b'foo': [b'bar', b'baz'],
  535. b'quux': [b'spam']}}.
  536. @type args: L{dict} of L{bytes} to L{list} of L{bytes}
  537. @ivar content: A file-like object giving the request body. This may be
  538. a file on disk, an L{io.BytesIO}, or some other type. The
  539. implementation is free to decide on a per-request basis.
  540. @type content: L{typing.BinaryIO}
  541. @ivar cookies: The cookies that will be sent in the response.
  542. @type cookies: L{list} of L{bytes}
  543. @type requestHeaders: L{http_headers.Headers}
  544. @ivar requestHeaders: All received HTTP request headers.
  545. @type responseHeaders: L{http_headers.Headers}
  546. @ivar responseHeaders: All HTTP response headers to be sent.
  547. @ivar notifications: A L{list} of L{Deferred}s which are waiting for
  548. notification that the response to this request has been finished
  549. (successfully or with an error). Don't use this attribute directly,
  550. instead use the L{Request.notifyFinish} method.
  551. @ivar _disconnected: A flag which is C{False} until the connection over
  552. which this request was received is closed and which is C{True} after
  553. that.
  554. @type _disconnected: L{bool}
  555. @ivar _log: A logger instance for request related messages.
  556. @type _log: L{twisted.logger.Logger}
  557. """
  558. producer = None
  559. finished = 0
  560. code = OK
  561. code_message = RESPONSES[OK]
  562. method = "(no method yet)"
  563. clientproto = b"(no clientproto yet)"
  564. uri = "(no uri yet)"
  565. startedWriting = 0
  566. chunked = 0
  567. sentLength = 0 # content-length of response, or total bytes sent via chunking
  568. etag = None
  569. lastModified = None
  570. args = None
  571. path = None
  572. content = None
  573. _forceSSL = 0
  574. _disconnected = False
  575. _log = Logger()
  576. def __init__(self, channel, queued=_QUEUED_SENTINEL):
  577. """
  578. @param channel: the channel we're connected to.
  579. @param queued: (deprecated) are we in the request queue, or can we
  580. start writing to the transport?
  581. """
  582. self.notifications = []
  583. self.channel = channel
  584. # Cache the client and server information, we'll need this
  585. # later to be serialized and sent with the request so CGIs
  586. # will work remotely
  587. self.client = self.channel.getPeer()
  588. self.host = self.channel.getHost()
  589. self.requestHeaders = Headers()
  590. self.received_cookies = {}
  591. self.responseHeaders = Headers()
  592. self.cookies = [] # outgoing cookies
  593. self.transport = self.channel.transport
  594. if queued is _QUEUED_SENTINEL:
  595. queued = False
  596. self.queued = queued
  597. def _cleanup(self):
  598. """
  599. Called when have finished responding and are no longer queued.
  600. """
  601. if self.producer:
  602. self._log.failure(
  603. '',
  604. Failure(
  605. RuntimeError(
  606. "Producer was not unregistered for %s" % (self.uri,)
  607. )
  608. )
  609. )
  610. self.unregisterProducer()
  611. self.channel.requestDone(self)
  612. del self.channel
  613. if self.content is not None:
  614. try:
  615. self.content.close()
  616. except OSError:
  617. # win32 suckiness, no idea why it does this
  618. pass
  619. del self.content
  620. for d in self.notifications:
  621. d.callback(None)
  622. self.notifications = []
  623. # methods for channel - end users should not use these
  624. def noLongerQueued(self):
  625. """
  626. Notify the object that it is no longer queued.
  627. We start writing whatever data we have to the transport, etc.
  628. This method is not intended for users.
  629. In 16.3 this method was changed to become a no-op, as L{Request}
  630. objects are now never queued.
  631. """
  632. pass
  633. def gotLength(self, length):
  634. """
  635. Called when HTTP channel got length of content in this request.
  636. This method is not intended for users.
  637. @param length: The length of the request body, as indicated by the
  638. request headers. L{None} if the request headers do not indicate a
  639. length.
  640. """
  641. self.content = _getContentFile(length)
  642. def parseCookies(self):
  643. """
  644. Parse cookie headers.
  645. This method is not intended for users.
  646. """
  647. cookieheaders = self.requestHeaders.getRawHeaders(b"cookie")
  648. if cookieheaders is None:
  649. return
  650. for cookietxt in cookieheaders:
  651. if cookietxt:
  652. for cook in cookietxt.split(b';'):
  653. cook = cook.lstrip()
  654. try:
  655. k, v = cook.split(b'=', 1)
  656. self.received_cookies[k] = v
  657. except ValueError:
  658. pass
  659. def handleContentChunk(self, data):
  660. """
  661. Write a chunk of data.
  662. This method is not intended for users.
  663. """
  664. self.content.write(data)
  665. def requestReceived(self, command, path, version):
  666. """
  667. Called by channel when all data has been received.
  668. This method is not intended for users.
  669. @type command: C{bytes}
  670. @param command: The HTTP verb of this request. This has the case
  671. supplied by the client (eg, it maybe "get" rather than "GET").
  672. @type path: C{bytes}
  673. @param path: The URI of this request.
  674. @type version: C{bytes}
  675. @param version: The HTTP version of this request.
  676. """
  677. self.content.seek(0,0)
  678. self.args = {}
  679. self.method, self.uri = command, path
  680. self.clientproto = version
  681. x = self.uri.split(b'?', 1)
  682. if len(x) == 1:
  683. self.path = self.uri
  684. else:
  685. self.path, argstring = x
  686. self.args = parse_qs(argstring, 1)
  687. # Argument processing
  688. args = self.args
  689. ctype = self.requestHeaders.getRawHeaders(b'content-type')
  690. clength = self.requestHeaders.getRawHeaders(b'content-length')
  691. if ctype is not None:
  692. ctype = ctype[0]
  693. if clength is not None:
  694. clength = clength[0]
  695. if self.method == b"POST" and ctype and clength:
  696. mfd = b'multipart/form-data'
  697. key, pdict = _parseHeader(ctype)
  698. pdict["CONTENT-LENGTH"] = clength
  699. if key == b'application/x-www-form-urlencoded':
  700. args.update(parse_qs(self.content.read(), 1))
  701. elif key == mfd:
  702. try:
  703. if _PY37PLUS:
  704. cgiArgs = cgi.parse_multipart(
  705. self.content, pdict, encoding='utf8',
  706. errors="surrogateescape")
  707. else:
  708. cgiArgs = cgi.parse_multipart(self.content, pdict)
  709. if not _PY37PLUS and _PY3:
  710. # The parse_multipart function on Python 3
  711. # decodes the header bytes as iso-8859-1 and
  712. # returns a str key -- we want bytes so encode
  713. # it back
  714. self.args.update({x.encode('iso-8859-1'): y
  715. for x, y in cgiArgs.items()})
  716. elif _PY37PLUS:
  717. # The parse_multipart function on Python 3.7+
  718. # decodes the header bytes as iso-8859-1 and
  719. # decodes the body bytes as utf8 with
  720. # surrogateescape -- we want bytes
  721. self.args.update({
  722. x.encode('iso-8859-1'): \
  723. [z.encode('utf8', "surrogateescape")
  724. if isinstance(z, str) else z for z in y]
  725. for x, y in cgiArgs.items()})
  726. else:
  727. self.args.update(cgiArgs)
  728. except Exception as e:
  729. # It was a bad request, or we got a signal.
  730. self.channel._respondToBadRequestAndDisconnect()
  731. if isinstance(e, (TypeError, ValueError, KeyError)):
  732. return
  733. else:
  734. # If it's not a userspace error from CGI, reraise
  735. raise
  736. self.content.seek(0, 0)
  737. self.process()
  738. def __repr__(self):
  739. """
  740. Return a string description of the request including such information
  741. as the request method and request URI.
  742. @return: A string loosely describing this L{Request} object.
  743. @rtype: L{str}
  744. """
  745. return '<%s at 0x%x method=%s uri=%s clientproto=%s>' % (
  746. self.__class__.__name__,
  747. id(self),
  748. nativeString(self.method),
  749. nativeString(self.uri),
  750. nativeString(self.clientproto))
  751. def process(self):
  752. """
  753. Override in subclasses.
  754. This method is not intended for users.
  755. """
  756. pass
  757. # consumer interface
  758. def registerProducer(self, producer, streaming):
  759. """
  760. Register a producer.
  761. """
  762. if self.producer:
  763. raise ValueError(
  764. "registering producer %s before previous one (%s) was "
  765. "unregistered" % (producer, self.producer))
  766. self.streamingProducer = streaming
  767. self.producer = producer
  768. self.channel.registerProducer(producer, streaming)
  769. def unregisterProducer(self):
  770. """
  771. Unregister the producer.
  772. """
  773. self.channel.unregisterProducer()
  774. self.producer = None
  775. # The following is the public interface that people should be
  776. # writing to.
  777. def getHeader(self, key):
  778. """
  779. Get an HTTP request header.
  780. @type key: C{bytes} or C{str}
  781. @param key: The name of the header to get the value of.
  782. @rtype: C{bytes} or C{str} or L{None}
  783. @return: The value of the specified header, or L{None} if that header
  784. was not present in the request. The string type of the result
  785. matches the type of L{key}.
  786. """
  787. value = self.requestHeaders.getRawHeaders(key)
  788. if value is not None:
  789. return value[-1]
  790. def getCookie(self, key):
  791. """
  792. Get a cookie that was sent from the network.
  793. @type key: C{bytes}
  794. @param key: The name of the cookie to get.
  795. @rtype: C{bytes} or C{None}
  796. @returns: The value of the specified cookie, or L{None} if that cookie
  797. was not present in the request.
  798. """
  799. return self.received_cookies.get(key)
  800. def notifyFinish(self):
  801. """
  802. Notify when the response to this request has finished.
  803. @note: There are some caveats around the reliability of the delivery of
  804. this notification.
  805. 1. If this L{Request}'s channel is paused, the notification
  806. will not be delivered. This can happen in one of two ways;
  807. either you can call C{request.transport.pauseProducing}
  808. yourself, or,
  809. 2. In order to deliver this notification promptly when a client
  810. disconnects, the reactor must continue reading from the
  811. transport, so that it can tell when the underlying network
  812. connection has gone away. Twisted Web will only keep
  813. reading up until a finite (small) maximum buffer size before
  814. it gives up and pauses the transport itself. If this
  815. occurs, you will not discover that the connection has gone
  816. away until a timeout fires or until the application attempts
  817. to send some data via L{Request.write}.
  818. 3. It is theoretically impossible to distinguish between
  819. successfully I{sending} a response and the peer successfully
  820. I{receiving} it. There are several networking edge cases
  821. where the L{Deferred}s returned by C{notifyFinish} will
  822. indicate success, but the data will never be received.
  823. There are also edge cases where the connection will appear
  824. to fail, but in reality the response was delivered. As a
  825. result, the information provided by the result of the
  826. L{Deferred}s returned by this method should be treated as a
  827. guess; do not make critical decisions in your applications
  828. based upon it.
  829. @rtype: L{Deferred}
  830. @return: A L{Deferred} which will be triggered when the request is
  831. finished -- with a L{None} value if the request finishes
  832. successfully or with an error if the request is interrupted by an
  833. error (for example, the client closing the connection prematurely).
  834. """
  835. self.notifications.append(Deferred())
  836. return self.notifications[-1]
  837. def finish(self):
  838. """
  839. Indicate that all response data has been written to this L{Request}.
  840. """
  841. if self._disconnected:
  842. raise RuntimeError(
  843. "Request.finish called on a request after its connection was lost; "
  844. "use Request.notifyFinish to keep track of this.")
  845. if self.finished:
  846. warnings.warn("Warning! request.finish called twice.", stacklevel=2)
  847. return
  848. if not self.startedWriting:
  849. # write headers
  850. self.write(b'')
  851. if self.chunked:
  852. # write last chunk and closing CRLF
  853. self.channel.write(b"0\r\n\r\n")
  854. # log request
  855. if (hasattr(self.channel, "factory") and
  856. self.channel.factory is not None):
  857. self.channel.factory.log(self)
  858. self.finished = 1
  859. if not self.queued:
  860. self._cleanup()
  861. def write(self, data):
  862. """
  863. Write some data as a result of an HTTP request. The first
  864. time this is called, it writes out response data.
  865. @type data: C{bytes}
  866. @param data: Some bytes to be sent as part of the response body.
  867. """
  868. if self.finished:
  869. raise RuntimeError('Request.write called on a request after '
  870. 'Request.finish was called.')
  871. if self._disconnected:
  872. # Don't attempt to write any data to a disconnected client.
  873. # The RuntimeError exception will be thrown as usual when
  874. # request.finish is called
  875. return
  876. if not self.startedWriting:
  877. self.startedWriting = 1
  878. version = self.clientproto
  879. code = intToBytes(self.code)
  880. reason = self.code_message
  881. headers = []
  882. # if we don't have a content length, we send data in
  883. # chunked mode, so that we can support pipelining in
  884. # persistent connections.
  885. if ((version == b"HTTP/1.1") and
  886. (self.responseHeaders.getRawHeaders(b'content-length') is None) and
  887. self.method != b"HEAD" and self.code not in NO_BODY_CODES):
  888. headers.append((b'Transfer-Encoding', b'chunked'))
  889. self.chunked = 1
  890. if self.lastModified is not None:
  891. if self.responseHeaders.hasHeader(b'last-modified'):
  892. self._log.info(
  893. "Warning: last-modified specified both in"
  894. " header list and lastModified attribute."
  895. )
  896. else:
  897. self.responseHeaders.setRawHeaders(
  898. b'last-modified',
  899. [datetimeToString(self.lastModified)])
  900. if self.etag is not None:
  901. self.responseHeaders.setRawHeaders(b'ETag', [self.etag])
  902. for name, values in self.responseHeaders.getAllRawHeaders():
  903. for value in values:
  904. headers.append((name, value))
  905. for cookie in self.cookies:
  906. headers.append((b'Set-Cookie', cookie))
  907. self.channel.writeHeaders(version, code, reason, headers)
  908. # if this is a "HEAD" request, we shouldn't return any data
  909. if self.method == b"HEAD":
  910. self.write = lambda data: None
  911. return
  912. # for certain result codes, we should never return any data
  913. if self.code in NO_BODY_CODES:
  914. self.write = lambda data: None
  915. return
  916. self.sentLength = self.sentLength + len(data)
  917. if data:
  918. if self.chunked:
  919. self.channel.writeSequence(toChunk(data))
  920. else:
  921. self.channel.write(data)
  922. def addCookie(self, k, v, expires=None, domain=None, path=None,
  923. max_age=None, comment=None, secure=None, httpOnly=False,
  924. sameSite=None):
  925. """
  926. Set an outgoing HTTP cookie.
  927. In general, you should consider using sessions instead of cookies, see
  928. L{twisted.web.server.Request.getSession} and the
  929. L{twisted.web.server.Session} class for details.
  930. @param k: cookie name
  931. @type k: L{bytes} or L{unicode}
  932. @param v: cookie value
  933. @type v: L{bytes} or L{unicode}
  934. @param expires: cookie expire attribute value in
  935. "Wdy, DD Mon YYYY HH:MM:SS GMT" format
  936. @type expires: L{bytes} or L{unicode}
  937. @param domain: cookie domain
  938. @type domain: L{bytes} or L{unicode}
  939. @param path: cookie path
  940. @type path: L{bytes} or L{unicode}
  941. @param max_age: cookie expiration in seconds from reception
  942. @type max_age: L{bytes} or L{unicode}
  943. @param comment: cookie comment
  944. @type comment: L{bytes} or L{unicode}
  945. @param secure: direct browser to send the cookie on encrypted
  946. connections only
  947. @type secure: L{bool}
  948. @param httpOnly: direct browser not to expose cookies through channels
  949. other than HTTP (and HTTPS) requests
  950. @type httpOnly: L{bool}
  951. @param sameSite: One of L{None} (default), C{'lax'} or C{'strict'}.
  952. Direct browsers not to send this cookie on cross-origin requests.
  953. Please see:
  954. U{https://tools.ietf.org/html/draft-west-first-party-cookies-07}
  955. @type sameSite: L{None}, L{bytes} or L{unicode}
  956. @raises: L{DeprecationWarning} if an argument is not L{bytes} or
  957. L{unicode}.
  958. L{ValueError} if the value for C{sameSite} is not supported.
  959. """
  960. def _ensureBytes(val):
  961. """
  962. Ensure that C{val} is bytes, encoding using UTF-8 if
  963. needed.
  964. @param val: L{bytes} or L{unicode}
  965. @return: L{bytes}
  966. """
  967. if val is None:
  968. # It's None, so we don't want to touch it
  969. return val
  970. if isinstance(val, bytes):
  971. return val
  972. else:
  973. return val.encode('utf8')
  974. def _sanitize(val):
  975. """
  976. Replace linear whitespace (C{\r}, C{\n}, C{\r\n}) and
  977. semicolons C{;} in C{val} with a single space.
  978. @param val: L{bytes}
  979. @return: L{bytes}
  980. """
  981. return _sanitizeLinearWhitespace(val).replace(b';', b' ')
  982. cookie = (
  983. _sanitize(_ensureBytes(k)) +
  984. b"=" +
  985. _sanitize(_ensureBytes(v)))
  986. if expires is not None:
  987. cookie = cookie + b"; Expires=" + _sanitize(_ensureBytes(expires))
  988. if domain is not None:
  989. cookie = cookie + b"; Domain=" + _sanitize(_ensureBytes(domain))
  990. if path is not None:
  991. cookie = cookie + b"; Path=" + _sanitize(_ensureBytes(path))
  992. if max_age is not None:
  993. cookie = cookie + b"; Max-Age=" + _sanitize(_ensureBytes(max_age))
  994. if comment is not None:
  995. cookie = cookie + b"; Comment=" + _sanitize(_ensureBytes(comment))
  996. if secure:
  997. cookie = cookie + b"; Secure"
  998. if httpOnly:
  999. cookie = cookie + b"; HttpOnly"
  1000. if sameSite:
  1001. sameSite = _ensureBytes(sameSite).lower()
  1002. if sameSite not in [b"lax", b"strict"]:
  1003. raise ValueError(
  1004. "Invalid value for sameSite: " + repr(sameSite))
  1005. cookie += b"; SameSite=" + sameSite
  1006. self.cookies.append(cookie)
  1007. def setResponseCode(self, code, message=None):
  1008. """
  1009. Set the HTTP response code.
  1010. @type code: L{int}
  1011. @type message: L{bytes}
  1012. """
  1013. if not isinstance(code, _intTypes):
  1014. raise TypeError("HTTP response code must be int or long")
  1015. self.code = code
  1016. if message:
  1017. if not isinstance(message, bytes):
  1018. raise TypeError("HTTP response status message must be bytes")
  1019. self.code_message = message
  1020. else:
  1021. self.code_message = RESPONSES.get(code, b"Unknown Status")
  1022. def setHeader(self, name, value):
  1023. """
  1024. Set an HTTP response header. Overrides any previously set values for
  1025. this header.
  1026. @type k: L{bytes} or L{str}
  1027. @param k: The name of the header for which to set the value.
  1028. @type v: L{bytes} or L{str}
  1029. @param v: The value to set for the named header. A L{str} will be
  1030. UTF-8 encoded, which may not interoperable with other
  1031. implementations. Avoid passing non-ASCII characters if possible.
  1032. """
  1033. self.responseHeaders.setRawHeaders(name, [value])
  1034. def redirect(self, url):
  1035. """
  1036. Utility function that does a redirect.
  1037. Set the response code to L{FOUND} and the I{Location} header to the
  1038. given URL.
  1039. The request should have C{finish()} called after this.
  1040. @param url: I{Location} header value.
  1041. @type url: L{bytes} or L{str}
  1042. """
  1043. self.setResponseCode(FOUND)
  1044. self.setHeader(b"location", url)
  1045. def setLastModified(self, when):
  1046. """
  1047. Set the C{Last-Modified} time for the response to this request.
  1048. If I am called more than once, I ignore attempts to set
  1049. Last-Modified earlier, only replacing the Last-Modified time
  1050. if it is to a later value.
  1051. If I am a conditional request, I may modify my response code
  1052. to L{NOT_MODIFIED} if appropriate for the time given.
  1053. @param when: The last time the resource being returned was
  1054. modified, in seconds since the epoch.
  1055. @type when: number
  1056. @return: If I am a I{If-Modified-Since} conditional request and
  1057. the time given is not newer than the condition, I return
  1058. L{http.CACHED<CACHED>} to indicate that you should write no
  1059. body. Otherwise, I return a false value.
  1060. """
  1061. # time.time() may be a float, but the HTTP-date strings are
  1062. # only good for whole seconds.
  1063. when = int(math.ceil(when))
  1064. if (not self.lastModified) or (self.lastModified < when):
  1065. self.lastModified = when
  1066. modifiedSince = self.getHeader(b'if-modified-since')
  1067. if modifiedSince:
  1068. firstPart = modifiedSince.split(b';', 1)[0]
  1069. try:
  1070. modifiedSince = stringToDatetime(firstPart)
  1071. except ValueError:
  1072. return None
  1073. if modifiedSince >= self.lastModified:
  1074. self.setResponseCode(NOT_MODIFIED)
  1075. return CACHED
  1076. return None
  1077. def setETag(self, etag):
  1078. """
  1079. Set an C{entity tag} for the outgoing response.
  1080. That's \"entity tag\" as in the HTTP/1.1 C{ETag} header, \"used
  1081. for comparing two or more entities from the same requested
  1082. resource.\"
  1083. If I am a conditional request, I may modify my response code
  1084. to L{NOT_MODIFIED} or L{PRECONDITION_FAILED}, if appropriate
  1085. for the tag given.
  1086. @param etag: The entity tag for the resource being returned.
  1087. @type etag: string
  1088. @return: If I am a C{If-None-Match} conditional request and
  1089. the tag matches one in the request, I return
  1090. L{http.CACHED<CACHED>} to indicate that you should write
  1091. no body. Otherwise, I return a false value.
  1092. """
  1093. if etag:
  1094. self.etag = etag
  1095. tags = self.getHeader(b"if-none-match")
  1096. if tags:
  1097. tags = tags.split()
  1098. if (etag in tags) or (b'*' in tags):
  1099. self.setResponseCode(((self.method in (b"HEAD", b"GET"))
  1100. and NOT_MODIFIED)
  1101. or PRECONDITION_FAILED)
  1102. return CACHED
  1103. return None
  1104. def getAllHeaders(self):
  1105. """
  1106. Return dictionary mapping the names of all received headers to the last
  1107. value received for each.
  1108. Since this method does not return all header information,
  1109. C{self.requestHeaders.getAllRawHeaders()} may be preferred.
  1110. """
  1111. headers = {}
  1112. for k, v in self.requestHeaders.getAllRawHeaders():
  1113. headers[k.lower()] = v[-1]
  1114. return headers
  1115. def getRequestHostname(self):
  1116. """
  1117. Get the hostname that the user passed in to the request.
  1118. This will either use the Host: header (if it is available) or the
  1119. host we are listening on if the header is unavailable.
  1120. @returns: the requested hostname
  1121. @rtype: C{bytes}
  1122. """
  1123. # XXX This method probably has no unit tests. I changed it a ton and
  1124. # nothing failed.
  1125. host = self.getHeader(b'host')
  1126. if host:
  1127. return host.split(b':', 1)[0]
  1128. return networkString(self.getHost().host)
  1129. def getHost(self):
  1130. """
  1131. Get my originally requesting transport's host.
  1132. Don't rely on the 'transport' attribute, since Request objects may be
  1133. copied remotely. For information on this method's return value, see
  1134. L{twisted.internet.tcp.Port}.
  1135. """
  1136. return self.host
  1137. def setHost(self, host, port, ssl=0):
  1138. """
  1139. Change the host and port the request thinks it's using.
  1140. This method is useful for working with reverse HTTP proxies (e.g.
  1141. both Squid and Apache's mod_proxy can do this), when the address
  1142. the HTTP client is using is different than the one we're listening on.
  1143. For example, Apache may be listening on https://www.example.com/, and
  1144. then forwarding requests to http://localhost:8080/, but we don't want
  1145. HTML produced by Twisted to say b'http://localhost:8080/', they should
  1146. say b'https://www.example.com/', so we do::
  1147. request.setHost(b'www.example.com', 443, ssl=1)
  1148. @type host: C{bytes}
  1149. @param host: The value to which to change the host header.
  1150. @type ssl: C{bool}
  1151. @param ssl: A flag which, if C{True}, indicates that the request is
  1152. considered secure (if C{True}, L{isSecure} will return C{True}).
  1153. """
  1154. self._forceSSL = ssl # set first so isSecure will work
  1155. if self.isSecure():
  1156. default = 443
  1157. else:
  1158. default = 80
  1159. if port == default:
  1160. hostHeader = host
  1161. else:
  1162. hostHeader = host + b":" + intToBytes(port)
  1163. self.requestHeaders.setRawHeaders(b"host", [hostHeader])
  1164. self.host = address.IPv4Address("TCP", host, port)
  1165. def getClientIP(self):
  1166. """
  1167. Return the IP address of the client who submitted this request.
  1168. This method is B{deprecated}. Use L{getClientAddress} instead.
  1169. @returns: the client IP address
  1170. @rtype: C{str}
  1171. """
  1172. if isinstance(self.client, (address.IPv4Address, address.IPv6Address)):
  1173. return self.client.host
  1174. else:
  1175. return None
  1176. def getClientAddress(self):
  1177. """
  1178. Return the address of the client who submitted this request.
  1179. This may not be a network address (e.g., a server listening on
  1180. a UNIX domain socket will cause this to return
  1181. L{UNIXAddress}). Callers must check the type of the returned
  1182. address.
  1183. @since: 18.4
  1184. @return: the client's address.
  1185. @rtype: L{IAddress}
  1186. """
  1187. return self.client
  1188. def isSecure(self):
  1189. """
  1190. Return L{True} if this request is using a secure transport.
  1191. Normally this method returns L{True} if this request's L{HTTPChannel}
  1192. instance is using a transport that implements
  1193. L{interfaces.ISSLTransport}.
  1194. This will also return L{True} if L{Request.setHost} has been called
  1195. with C{ssl=True}.
  1196. @returns: L{True} if this request is secure
  1197. @rtype: C{bool}
  1198. """
  1199. if self._forceSSL:
  1200. return True
  1201. channel = getattr(self, 'channel', None)
  1202. if channel is None:
  1203. return False
  1204. return channel.isSecure()
  1205. def _authorize(self):
  1206. # Authorization, (mostly) per the RFC
  1207. try:
  1208. authh = self.getHeader(b"Authorization")
  1209. if not authh:
  1210. self.user = self.password = ''
  1211. return
  1212. bas, upw = authh.split()
  1213. if bas.lower() != b"basic":
  1214. raise ValueError()
  1215. upw = base64.decodestring(upw)
  1216. self.user, self.password = upw.split(b':', 1)
  1217. except (binascii.Error, ValueError):
  1218. self.user = self.password = ""
  1219. except:
  1220. self._log.failure('')
  1221. self.user = self.password = ""
  1222. def getUser(self):
  1223. """
  1224. Return the HTTP user sent with this request, if any.
  1225. If no user was supplied, return the empty string.
  1226. @returns: the HTTP user, if any
  1227. @rtype: C{bytes}
  1228. """
  1229. try:
  1230. return self.user
  1231. except:
  1232. pass
  1233. self._authorize()
  1234. return self.user
  1235. def getPassword(self):
  1236. """
  1237. Return the HTTP password sent with this request, if any.
  1238. If no password was supplied, return the empty string.
  1239. @returns: the HTTP password, if any
  1240. @rtype: C{bytes}
  1241. """
  1242. try:
  1243. return self.password
  1244. except:
  1245. pass
  1246. self._authorize()
  1247. return self.password
  1248. def connectionLost(self, reason):
  1249. """
  1250. There is no longer a connection for this request to respond over.
  1251. Clean up anything which can't be useful anymore.
  1252. """
  1253. self._disconnected = True
  1254. self.channel = None
  1255. if self.content is not None:
  1256. self.content.close()
  1257. for d in self.notifications:
  1258. d.errback(reason)
  1259. self.notifications = []
  1260. def loseConnection(self):
  1261. """
  1262. Pass the loseConnection through to the underlying channel.
  1263. """
  1264. if self.channel is not None:
  1265. self.channel.loseConnection()
  1266. def __eq__(self, other):
  1267. """
  1268. Determines if two requests are the same object.
  1269. @param other: Another object whose identity will be compared
  1270. to this instance's.
  1271. @return: L{True} when the two are the same object and L{False}
  1272. when not.
  1273. @rtype: L{bool}
  1274. """
  1275. # When other is not an instance of request, return
  1276. # NotImplemented so that Python uses other.__eq__ to perform
  1277. # the comparison. This ensures that a Request proxy generated
  1278. # by proxyForInterface compares equal to an actual Request
  1279. # instanceby turning request != proxy into proxy != request.
  1280. if isinstance(other, Request):
  1281. return self is other
  1282. return NotImplemented
  1283. def __ne__(self, other):
  1284. """
  1285. Determines if two requests are not the same object.
  1286. @param other: Another object whose identity will be compared
  1287. to this instance's.
  1288. @return: L{True} when the two are not the same object and
  1289. L{False} when they are.
  1290. @rtype: L{bool}
  1291. """
  1292. # When other is not an instance of request, return
  1293. # NotImplemented so that Python uses other.__ne__ to perform
  1294. # the comparison. This ensures that a Request proxy generated
  1295. # by proxyForInterface can compare equal to an actual Request
  1296. # instance by turning request != proxy into proxy != request.
  1297. if isinstance(other, Request):
  1298. return self is not other
  1299. return NotImplemented
  1300. def __hash__(self):
  1301. """
  1302. A C{Request} is hashable so that it can be used as a mapping key.
  1303. @return: A C{int} based on the instance's identity.
  1304. """
  1305. return id(self)
  1306. Request.getClientIP = deprecated(
  1307. Version('Twisted', 18, 4, 0),
  1308. replacement="getClientAddress",
  1309. )(Request.getClientIP)
  1310. Request.noLongerQueued = deprecated(
  1311. Version("Twisted", 16, 3, 0))(Request.noLongerQueued)
  1312. class _DataLoss(Exception):
  1313. """
  1314. L{_DataLoss} indicates that not all of a message body was received. This
  1315. is only one of several possible exceptions which may indicate that data
  1316. was lost. Because of this, it should not be checked for by
  1317. specifically; any unexpected exception should be treated as having
  1318. caused data loss.
  1319. """
  1320. class PotentialDataLoss(Exception):
  1321. """
  1322. L{PotentialDataLoss} may be raised by a transfer encoding decoder's
  1323. C{noMoreData} method to indicate that it cannot be determined if the
  1324. entire response body has been delivered. This only occurs when making
  1325. requests to HTTP servers which do not set I{Content-Length} or a
  1326. I{Transfer-Encoding} in the response because in this case the end of the
  1327. response is indicated by the connection being closed, an event which may
  1328. also be due to a transient network problem or other error.
  1329. """
  1330. class _MalformedChunkedDataError(Exception):
  1331. """
  1332. C{_ChunkedTranferDecoder} raises L{_MalformedChunkedDataError} from its
  1333. C{dataReceived} method when it encounters malformed data. This exception
  1334. indicates a client-side error. If this exception is raised, the connection
  1335. should be dropped with a 400 error.
  1336. """
  1337. class _IdentityTransferDecoder(object):
  1338. """
  1339. Protocol for accumulating bytes up to a specified length. This handles the
  1340. case where no I{Transfer-Encoding} is specified.
  1341. @ivar contentLength: Counter keeping track of how many more bytes there are
  1342. to receive.
  1343. @ivar dataCallback: A one-argument callable which will be invoked each
  1344. time application data is received.
  1345. @ivar finishCallback: A one-argument callable which will be invoked when
  1346. the terminal chunk is received. It will be invoked with all bytes
  1347. which were delivered to this protocol which came after the terminal
  1348. chunk.
  1349. """
  1350. def __init__(self, contentLength, dataCallback, finishCallback):
  1351. self.contentLength = contentLength
  1352. self.dataCallback = dataCallback
  1353. self.finishCallback = finishCallback
  1354. def dataReceived(self, data):
  1355. """
  1356. Interpret the next chunk of bytes received. Either deliver them to the
  1357. data callback or invoke the finish callback if enough bytes have been
  1358. received.
  1359. @raise RuntimeError: If the finish callback has already been invoked
  1360. during a previous call to this methood.
  1361. """
  1362. if self.dataCallback is None:
  1363. raise RuntimeError(
  1364. "_IdentityTransferDecoder cannot decode data after finishing")
  1365. if self.contentLength is None:
  1366. self.dataCallback(data)
  1367. elif len(data) < self.contentLength:
  1368. self.contentLength -= len(data)
  1369. self.dataCallback(data)
  1370. else:
  1371. # Make the state consistent before invoking any code belonging to
  1372. # anyone else in case noMoreData ends up being called beneath this
  1373. # stack frame.
  1374. contentLength = self.contentLength
  1375. dataCallback = self.dataCallback
  1376. finishCallback = self.finishCallback
  1377. self.dataCallback = self.finishCallback = None
  1378. self.contentLength = 0
  1379. dataCallback(data[:contentLength])
  1380. finishCallback(data[contentLength:])
  1381. def noMoreData(self):
  1382. """
  1383. All data which will be delivered to this decoder has been. Check to
  1384. make sure as much data as was expected has been received.
  1385. @raise PotentialDataLoss: If the content length is unknown.
  1386. @raise _DataLoss: If the content length is known and fewer than that
  1387. many bytes have been delivered.
  1388. @return: L{None}
  1389. """
  1390. finishCallback = self.finishCallback
  1391. self.dataCallback = self.finishCallback = None
  1392. if self.contentLength is None:
  1393. finishCallback(b'')
  1394. raise PotentialDataLoss()
  1395. elif self.contentLength != 0:
  1396. raise _DataLoss()
  1397. class _ChunkedTransferDecoder(object):
  1398. """
  1399. Protocol for decoding I{chunked} Transfer-Encoding, as defined by RFC 2616,
  1400. section 3.6.1. This protocol can interpret the contents of a request or
  1401. response body which uses the I{chunked} Transfer-Encoding. It cannot
  1402. interpret any of the rest of the HTTP protocol.
  1403. It may make sense for _ChunkedTransferDecoder to be an actual IProtocol
  1404. implementation. Currently, the only user of this class will only ever
  1405. call dataReceived on it. However, it might be an improvement if the
  1406. user could connect this to a transport and deliver connection lost
  1407. notification. This way, `dataCallback` becomes `self.transport.write`
  1408. and perhaps `finishCallback` becomes `self.transport.loseConnection()`
  1409. (although I'm not sure where the extra data goes in that case). This
  1410. could also allow this object to indicate to the receiver of data that
  1411. the stream was not completely received, an error case which should be
  1412. noticed. -exarkun
  1413. @ivar dataCallback: A one-argument callable which will be invoked each
  1414. time application data is received.
  1415. @ivar finishCallback: A one-argument callable which will be invoked when
  1416. the terminal chunk is received. It will be invoked with all bytes
  1417. which were delivered to this protocol which came after the terminal
  1418. chunk.
  1419. @ivar length: Counter keeping track of how many more bytes in a chunk there
  1420. are to receive.
  1421. @ivar state: One of C{'CHUNK_LENGTH'}, C{'CRLF'}, C{'TRAILER'},
  1422. C{'BODY'}, or C{'FINISHED'}. For C{'CHUNK_LENGTH'}, data for the
  1423. chunk length line is currently being read. For C{'CRLF'}, the CR LF
  1424. pair which follows each chunk is being read. For C{'TRAILER'}, the CR
  1425. LF pair which follows the terminal 0-length chunk is currently being
  1426. read. For C{'BODY'}, the contents of a chunk are being read. For
  1427. C{'FINISHED'}, the last chunk has been completely read and no more
  1428. input is valid.
  1429. """
  1430. state = 'CHUNK_LENGTH'
  1431. def __init__(self, dataCallback, finishCallback):
  1432. self.dataCallback = dataCallback
  1433. self.finishCallback = finishCallback
  1434. self._buffer = b''
  1435. def _dataReceived_CHUNK_LENGTH(self, data):
  1436. if b'\r\n' in data:
  1437. line, rest = data.split(b'\r\n', 1)
  1438. parts = line.split(b';')
  1439. try:
  1440. self.length = int(parts[0], 16)
  1441. except ValueError:
  1442. raise _MalformedChunkedDataError(
  1443. "Chunk-size must be an integer.")
  1444. if self.length == 0:
  1445. self.state = 'TRAILER'
  1446. else:
  1447. self.state = 'BODY'
  1448. return rest
  1449. else:
  1450. self._buffer = data
  1451. return b''
  1452. def _dataReceived_CRLF(self, data):
  1453. if data.startswith(b'\r\n'):
  1454. self.state = 'CHUNK_LENGTH'
  1455. return data[2:]
  1456. else:
  1457. self._buffer = data
  1458. return b''
  1459. def _dataReceived_TRAILER(self, data):
  1460. if data.startswith(b'\r\n'):
  1461. data = data[2:]
  1462. self.state = 'FINISHED'
  1463. self.finishCallback(data)
  1464. else:
  1465. self._buffer = data
  1466. return b''
  1467. def _dataReceived_BODY(self, data):
  1468. if len(data) >= self.length:
  1469. chunk, data = data[:self.length], data[self.length:]
  1470. self.dataCallback(chunk)
  1471. self.state = 'CRLF'
  1472. return data
  1473. elif len(data) < self.length:
  1474. self.length -= len(data)
  1475. self.dataCallback(data)
  1476. return b''
  1477. def _dataReceived_FINISHED(self, data):
  1478. raise RuntimeError(
  1479. "_ChunkedTransferDecoder.dataReceived called after last "
  1480. "chunk was processed")
  1481. def dataReceived(self, data):
  1482. """
  1483. Interpret data from a request or response body which uses the
  1484. I{chunked} Transfer-Encoding.
  1485. """
  1486. data = self._buffer + data
  1487. self._buffer = b''
  1488. while data:
  1489. data = getattr(self, '_dataReceived_%s' % (self.state,))(data)
  1490. def noMoreData(self):
  1491. """
  1492. Verify that all data has been received. If it has not been, raise
  1493. L{_DataLoss}.
  1494. """
  1495. if self.state != 'FINISHED':
  1496. raise _DataLoss(
  1497. "Chunked decoder in %r state, still expecting more data to "
  1498. "get to 'FINISHED' state." % (self.state,))
  1499. @implementer(interfaces.IPushProducer)
  1500. class _NoPushProducer(object):
  1501. """
  1502. A no-op version of L{interfaces.IPushProducer}, used to abstract over the
  1503. possibility that a L{HTTPChannel} transport does not provide
  1504. L{IPushProducer}.
  1505. """
  1506. def pauseProducing(self):
  1507. """
  1508. Pause producing data.
  1509. Tells a producer that it has produced too much data to process for
  1510. the time being, and to stop until resumeProducing() is called.
  1511. """
  1512. pass
  1513. def resumeProducing(self):
  1514. """
  1515. Resume producing data.
  1516. This tells a producer to re-add itself to the main loop and produce
  1517. more data for its consumer.
  1518. """
  1519. pass
  1520. def registerProducer(self, producer, streaming):
  1521. """
  1522. Register to receive data from a producer.
  1523. @param producer: The producer to register.
  1524. @param streaming: Whether this is a streaming producer or not.
  1525. """
  1526. pass
  1527. def unregisterProducer(self):
  1528. """
  1529. Stop consuming data from a producer, without disconnecting.
  1530. """
  1531. pass
  1532. @implementer(interfaces.ITransport,
  1533. interfaces.IPushProducer,
  1534. interfaces.IConsumer)
  1535. class HTTPChannel(basic.LineReceiver, policies.TimeoutMixin):
  1536. """
  1537. A receiver for HTTP requests.
  1538. The L{HTTPChannel} provides L{interfaces.ITransport} and
  1539. L{interfaces.IConsumer} to the L{Request} objects it creates. It also
  1540. implements L{interfaces.IPushProducer} to C{self.transport}, allowing the
  1541. transport to pause it.
  1542. @ivar MAX_LENGTH: Maximum length for initial request line and each line
  1543. from the header.
  1544. @ivar _transferDecoder: L{None} or a decoder instance if the request body
  1545. uses the I{chunked} Transfer-Encoding.
  1546. @type _transferDecoder: L{_ChunkedTransferDecoder}
  1547. @ivar maxHeaders: Maximum number of headers allowed per request.
  1548. @type maxHeaders: C{int}
  1549. @ivar totalHeadersSize: Maximum bytes for request line plus all headers
  1550. from the request.
  1551. @type totalHeadersSize: C{int}
  1552. @ivar _receivedHeaderSize: Bytes received so far for the header.
  1553. @type _receivedHeaderSize: C{int}
  1554. @ivar _handlingRequest: Whether a request is currently being processed.
  1555. @type _handlingRequest: L{bool}
  1556. @ivar _dataBuffer: Any data that has been received from the connection
  1557. while processing an outstanding request.
  1558. @type _dataBuffer: L{list} of L{bytes}
  1559. @ivar _networkProducer: Either the transport, if it provides
  1560. L{interfaces.IPushProducer}, or a null implementation of
  1561. L{interfaces.IPushProducer}. Used to attempt to prevent the transport
  1562. from producing excess data when we're responding to a request.
  1563. @type _networkProducer: L{interfaces.IPushProducer}
  1564. @ivar _requestProducer: If the L{Request} object or anything it calls
  1565. registers itself as an L{interfaces.IProducer}, it will be stored here.
  1566. This is used to create a producing pipeline: pause/resume producing
  1567. methods will be propagated from the C{transport}, through the
  1568. L{HTTPChannel} instance, to the c{_requestProducer}.
  1569. The reason we proxy through the producing methods rather than the old
  1570. behaviour (where we literally just set the L{Request} object as the
  1571. producer on the transport) is because we want to be able to exert
  1572. backpressure on the client to prevent it from sending in arbitrarily
  1573. many requests without ever reading responses. Essentially, if the
  1574. client never reads our responses we will eventually stop reading its
  1575. requests.
  1576. @type _requestProducer: L{interfaces.IPushProducer}
  1577. @ivar _requestProducerStreaming: A boolean that tracks whether the producer
  1578. on the L{Request} side of this channel has registered itself as a
  1579. L{interfaces.IPushProducer} or an L{interfaces.IPullProducer}.
  1580. @type _requestProducerStreaming: L{bool} or L{None}
  1581. @ivar _waitingForTransport: A boolean that tracks whether the transport has
  1582. asked us to stop producing. This is used to keep track of what we're
  1583. waiting for: if the transport has asked us to stop producing then we
  1584. don't want to unpause the transport until it asks us to produce again.
  1585. @type _waitingForTransport: L{bool}
  1586. @ivar abortTimeout: The number of seconds to wait after we attempt to shut
  1587. the transport down cleanly to give up and forcibly terminate it. This
  1588. is only used when we time a connection out, to prevent errors causing
  1589. the FD to get leaked. If this is L{None}, we will wait forever.
  1590. @type abortTimeout: L{int}
  1591. @ivar _abortingCall: The L{twisted.internet.base.DelayedCall} that will be
  1592. used to forcibly close the transport if it doesn't close cleanly.
  1593. @type _abortingCall: L{twisted.internet.base.DelayedCall}
  1594. @ivar _optimisticEagerReadSize: When a resource takes a long time to answer
  1595. a request (via L{twisted.web.server.NOT_DONE_YET}, hopefully one day by
  1596. a L{Deferred}), we would like to be able to let that resource know
  1597. about the underlying transport disappearing as promptly as possible,
  1598. via L{Request.notifyFinish}, and therefore via
  1599. C{self.requests[...].connectionLost()} on this L{HTTPChannel}.
  1600. However, in order to simplify application logic, we implement
  1601. head-of-line blocking, and do not relay pipelined requests to the
  1602. application until the previous request has been answered. This means
  1603. that said application cannot dispose of any entity-body that comes in
  1604. from those subsequent requests, which may be arbitrarily large, and it
  1605. may need to be buffered in memory.
  1606. To implement this tradeoff between prompt notification when possible
  1607. (in the most frequent case of non-pipelined requests) and correct
  1608. behavior when not (say, if a client sends a very long-running GET
  1609. request followed by a PUT request with a very large body) we will
  1610. continue reading pipelined requests into C{self._dataBuffer} up to a
  1611. given limit.
  1612. C{_optimisticEagerReadSize} is the number of bytes we will accept from
  1613. the client and buffer before pausing the transport.
  1614. This behavior has been in place since Twisted 17.9.0 .
  1615. @type _optimisticEagerReadSize: L{int}
  1616. """
  1617. maxHeaders = 500
  1618. totalHeadersSize = 16384
  1619. abortTimeout = 15
  1620. length = 0
  1621. persistent = 1
  1622. __header = b''
  1623. __first_line = 1
  1624. __content = None
  1625. # set in instances or subclasses
  1626. requestFactory = Request
  1627. _savedTimeOut = None
  1628. _receivedHeaderCount = 0
  1629. _receivedHeaderSize = 0
  1630. _requestProducer = None
  1631. _requestProducerStreaming = None
  1632. _waitingForTransport = False
  1633. _abortingCall = None
  1634. _optimisticEagerReadSize = 0x4000
  1635. _log = Logger()
  1636. def __init__(self):
  1637. # the request queue
  1638. self.requests = []
  1639. self._handlingRequest = False
  1640. self._dataBuffer = []
  1641. self._transferDecoder = None
  1642. def connectionMade(self):
  1643. self.setTimeout(self.timeOut)
  1644. self._networkProducer = interfaces.IPushProducer(
  1645. self.transport, _NoPushProducer()
  1646. )
  1647. self._networkProducer.registerProducer(self, True)
  1648. def lineReceived(self, line):
  1649. """
  1650. Called for each line from request until the end of headers when
  1651. it enters binary mode.
  1652. """
  1653. self.resetTimeout()
  1654. self._receivedHeaderSize += len(line)
  1655. if (self._receivedHeaderSize > self.totalHeadersSize):
  1656. self._respondToBadRequestAndDisconnect()
  1657. return
  1658. if self.__first_line:
  1659. # if this connection is not persistent, drop any data which
  1660. # the client (illegally) sent after the last request.
  1661. if not self.persistent:
  1662. self.dataReceived = self.lineReceived = lambda *args: None
  1663. return
  1664. # IE sends an extraneous empty line (\r\n) after a POST request;
  1665. # eat up such a line, but only ONCE
  1666. if not line and self.__first_line == 1:
  1667. self.__first_line = 2
  1668. return
  1669. # create a new Request object
  1670. if INonQueuedRequestFactory.providedBy(self.requestFactory):
  1671. request = self.requestFactory(self)
  1672. else:
  1673. request = self.requestFactory(self, len(self.requests))
  1674. self.requests.append(request)
  1675. self.__first_line = 0
  1676. parts = line.split()
  1677. if len(parts) != 3:
  1678. self._respondToBadRequestAndDisconnect()
  1679. return
  1680. command, request, version = parts
  1681. try:
  1682. command.decode("ascii")
  1683. except UnicodeDecodeError:
  1684. self._respondToBadRequestAndDisconnect()
  1685. return
  1686. self._command = command
  1687. self._path = request
  1688. self._version = version
  1689. elif line == b'':
  1690. # End of headers.
  1691. if self.__header:
  1692. ok = self.headerReceived(self.__header)
  1693. # If the last header we got is invalid, we MUST NOT proceed
  1694. # with processing. We'll have sent a 400 anyway, so just stop.
  1695. if not ok:
  1696. return
  1697. self.__header = b''
  1698. self.allHeadersReceived()
  1699. if self.length == 0:
  1700. self.allContentReceived()
  1701. else:
  1702. self.setRawMode()
  1703. elif line[0] in b' \t':
  1704. # Continuation of a multi line header.
  1705. self.__header = self.__header + b'\n' + line
  1706. # Regular header line.
  1707. # Processing of header line is delayed to allow accumulating multi
  1708. # line headers.
  1709. else:
  1710. if self.__header:
  1711. self.headerReceived(self.__header)
  1712. self.__header = line
  1713. def _finishRequestBody(self, data):
  1714. self.allContentReceived()
  1715. self._dataBuffer.append(data)
  1716. def headerReceived(self, line):
  1717. """
  1718. Do pre-processing (for content-length) and store this header away.
  1719. Enforce the per-request header limit.
  1720. @type line: C{bytes}
  1721. @param line: A line from the header section of a request, excluding the
  1722. line delimiter.
  1723. @return: A flag indicating whether the header was valid.
  1724. @rtype: L{bool}
  1725. """
  1726. try:
  1727. header, data = line.split(b':', 1)
  1728. except ValueError:
  1729. self._respondToBadRequestAndDisconnect()
  1730. return False
  1731. header = header.lower()
  1732. data = data.strip()
  1733. if header == b'content-length':
  1734. try:
  1735. self.length = int(data)
  1736. except ValueError:
  1737. self._respondToBadRequestAndDisconnect()
  1738. self.length = None
  1739. return False
  1740. self._transferDecoder = _IdentityTransferDecoder(
  1741. self.length, self.requests[-1].handleContentChunk, self._finishRequestBody)
  1742. elif header == b'transfer-encoding' and data.lower() == b'chunked':
  1743. # XXX Rather poorly tested code block, apparently only exercised by
  1744. # test_chunkedEncoding
  1745. self.length = None
  1746. self._transferDecoder = _ChunkedTransferDecoder(
  1747. self.requests[-1].handleContentChunk, self._finishRequestBody)
  1748. reqHeaders = self.requests[-1].requestHeaders
  1749. values = reqHeaders.getRawHeaders(header)
  1750. if values is not None:
  1751. values.append(data)
  1752. else:
  1753. reqHeaders.setRawHeaders(header, [data])
  1754. self._receivedHeaderCount += 1
  1755. if self._receivedHeaderCount > self.maxHeaders:
  1756. self._respondToBadRequestAndDisconnect()
  1757. return False
  1758. return True
  1759. def allContentReceived(self):
  1760. command = self._command
  1761. path = self._path
  1762. version = self._version
  1763. # reset ALL state variables, so we don't interfere with next request
  1764. self.length = 0
  1765. self._receivedHeaderCount = 0
  1766. self._receivedHeaderSize = 0
  1767. self.__first_line = 1
  1768. self._transferDecoder = None
  1769. del self._command, self._path, self._version
  1770. # Disable the idle timeout, in case this request takes a long
  1771. # time to finish generating output.
  1772. if self.timeOut:
  1773. self._savedTimeOut = self.setTimeout(None)
  1774. self._handlingRequest = True
  1775. req = self.requests[-1]
  1776. req.requestReceived(command, path, version)
  1777. def dataReceived(self, data):
  1778. """
  1779. Data was received from the network. Process it.
  1780. """
  1781. # If we're currently handling a request, buffer this data.
  1782. if self._handlingRequest:
  1783. self._dataBuffer.append(data)
  1784. if (
  1785. (sum(map(len, self._dataBuffer)) >
  1786. self._optimisticEagerReadSize)
  1787. and not self._waitingForTransport
  1788. ):
  1789. # If we received more data than a small limit while processing
  1790. # the head-of-line request, apply TCP backpressure to our peer
  1791. # to get them to stop sending more request data until we're
  1792. # ready. See docstring for _optimisticEagerReadSize above.
  1793. self._networkProducer.pauseProducing()
  1794. return
  1795. return basic.LineReceiver.dataReceived(self, data)
  1796. def rawDataReceived(self, data):
  1797. self.resetTimeout()
  1798. try:
  1799. self._transferDecoder.dataReceived(data)
  1800. except _MalformedChunkedDataError:
  1801. self._respondToBadRequestAndDisconnect()
  1802. def allHeadersReceived(self):
  1803. req = self.requests[-1]
  1804. req.parseCookies()
  1805. self.persistent = self.checkPersistence(req, self._version)
  1806. req.gotLength(self.length)
  1807. # Handle 'Expect: 100-continue' with automated 100 response code,
  1808. # a simplistic implementation of RFC 2686 8.2.3:
  1809. expectContinue = req.requestHeaders.getRawHeaders(b'expect')
  1810. if (expectContinue and expectContinue[0].lower() == b'100-continue' and
  1811. self._version == b'HTTP/1.1'):
  1812. self._send100Continue()
  1813. def checkPersistence(self, request, version):
  1814. """
  1815. Check if the channel should close or not.
  1816. @param request: The request most recently received over this channel
  1817. against which checks will be made to determine if this connection
  1818. can remain open after a matching response is returned.
  1819. @type version: C{bytes}
  1820. @param version: The version of the request.
  1821. @rtype: C{bool}
  1822. @return: A flag which, if C{True}, indicates that this connection may
  1823. remain open to receive another request; if C{False}, the connection
  1824. must be closed in order to indicate the completion of the response
  1825. to C{request}.
  1826. """
  1827. connection = request.requestHeaders.getRawHeaders(b'connection')
  1828. if connection:
  1829. tokens = [t.lower() for t in connection[0].split(b' ')]
  1830. else:
  1831. tokens = []
  1832. # Once any HTTP 0.9 or HTTP 1.0 request is received, the connection is
  1833. # no longer allowed to be persistent. At this point in processing the
  1834. # request, we don't yet know if it will be possible to set a
  1835. # Content-Length in the response. If it is not, then the connection
  1836. # will have to be closed to end an HTTP 0.9 or HTTP 1.0 response.
  1837. # If the checkPersistence call happened later, after the Content-Length
  1838. # has been determined (or determined not to be set), it would probably
  1839. # be possible to have persistent connections with HTTP 0.9 and HTTP 1.0.
  1840. # This may not be worth the effort, though. Just use HTTP 1.1, okay?
  1841. if version == b"HTTP/1.1":
  1842. if b'close' in tokens:
  1843. request.responseHeaders.setRawHeaders(b'connection', [b'close'])
  1844. return False
  1845. else:
  1846. return True
  1847. else:
  1848. return False
  1849. def requestDone(self, request):
  1850. """
  1851. Called by first request in queue when it is done.
  1852. """
  1853. if request != self.requests[0]: raise TypeError
  1854. del self.requests[0]
  1855. # We should only resume the producer if we're not waiting for the
  1856. # transport.
  1857. if not self._waitingForTransport:
  1858. self._networkProducer.resumeProducing()
  1859. if self.persistent:
  1860. self._handlingRequest = False
  1861. if self._savedTimeOut:
  1862. self.setTimeout(self._savedTimeOut)
  1863. # Receive our buffered data, if any.
  1864. data = b''.join(self._dataBuffer)
  1865. self._dataBuffer = []
  1866. self.setLineMode(data)
  1867. else:
  1868. self.loseConnection()
  1869. def timeoutConnection(self):
  1870. self._log.info(
  1871. "Timing out client: {peer}",
  1872. peer=str(self.transport.getPeer())
  1873. )
  1874. if self.abortTimeout is not None:
  1875. # We use self.callLater because that's what TimeoutMixin does.
  1876. self._abortingCall = self.callLater(
  1877. self.abortTimeout, self.forceAbortClient
  1878. )
  1879. self.loseConnection()
  1880. def forceAbortClient(self):
  1881. """
  1882. Called if C{abortTimeout} seconds have passed since the timeout fired,
  1883. and the connection still hasn't gone away. This can really only happen
  1884. on extremely bad connections or when clients are maliciously attempting
  1885. to keep connections open.
  1886. """
  1887. self._log.info(
  1888. "Forcibly timing out client: {peer}",
  1889. peer=str(self.transport.getPeer())
  1890. )
  1891. # We want to lose track of the _abortingCall so that no-one tries to
  1892. # cancel it.
  1893. self._abortingCall = None
  1894. self.transport.abortConnection()
  1895. def connectionLost(self, reason):
  1896. self.setTimeout(None)
  1897. for request in self.requests:
  1898. request.connectionLost(reason)
  1899. # If we were going to force-close the transport, we don't have to now.
  1900. if self._abortingCall is not None:
  1901. self._abortingCall.cancel()
  1902. self._abortingCall = None
  1903. def isSecure(self):
  1904. """
  1905. Return L{True} if this channel is using a secure transport.
  1906. Normally this method returns L{True} if this instance is using a
  1907. transport that implements L{interfaces.ISSLTransport}.
  1908. @returns: L{True} if this request is secure
  1909. @rtype: C{bool}
  1910. """
  1911. if interfaces.ISSLTransport(self.transport, None) is not None:
  1912. return True
  1913. return False
  1914. def writeHeaders(self, version, code, reason, headers):
  1915. """
  1916. Called by L{Request} objects to write a complete set of HTTP headers to
  1917. a transport.
  1918. @param version: The HTTP version in use.
  1919. @type version: L{bytes}
  1920. @param code: The HTTP status code to write.
  1921. @type code: L{bytes}
  1922. @param reason: The HTTP reason phrase to write.
  1923. @type reason: L{bytes}
  1924. @param headers: The headers to write to the transport.
  1925. @type headers: L{twisted.web.http_headers.Headers}
  1926. """
  1927. sanitizedHeaders = Headers()
  1928. for name, value in headers:
  1929. sanitizedHeaders.addRawHeader(name, value)
  1930. responseLine = version + b" " + code + b" " + reason + b"\r\n"
  1931. headerSequence = [responseLine]
  1932. headerSequence.extend(
  1933. name + b': ' + value + b"\r\n"
  1934. for name, values in sanitizedHeaders.getAllRawHeaders()
  1935. for value in values
  1936. )
  1937. headerSequence.append(b"\r\n")
  1938. self.transport.writeSequence(headerSequence)
  1939. def write(self, data):
  1940. """
  1941. Called by L{Request} objects to write response data.
  1942. @param data: The data chunk to write to the stream.
  1943. @type data: L{bytes}
  1944. @return: L{None}
  1945. """
  1946. self.transport.write(data)
  1947. def writeSequence(self, iovec):
  1948. """
  1949. Write a list of strings to the HTTP response.
  1950. @param iovec: A list of byte strings to write to the stream.
  1951. @type data: L{list} of L{bytes}
  1952. @return: L{None}
  1953. """
  1954. self.transport.writeSequence(iovec)
  1955. def getPeer(self):
  1956. """
  1957. Get the remote address of this connection.
  1958. @return: An L{IAddress} provider.
  1959. """
  1960. return self.transport.getPeer()
  1961. def getHost(self):
  1962. """
  1963. Get the local address of this connection.
  1964. @return: An L{IAddress} provider.
  1965. """
  1966. return self.transport.getHost()
  1967. def loseConnection(self):
  1968. """
  1969. Closes the connection. Will write any data that is pending to be sent
  1970. on the network, but if this response has not yet been written to the
  1971. network will not write anything.
  1972. @return: L{None}
  1973. """
  1974. self._networkProducer.unregisterProducer()
  1975. return self.transport.loseConnection()
  1976. def registerProducer(self, producer, streaming):
  1977. """
  1978. Register to receive data from a producer.
  1979. This sets self to be a consumer for a producer. When this object runs
  1980. out of data (as when a send(2) call on a socket succeeds in moving the
  1981. last data from a userspace buffer into a kernelspace buffer), it will
  1982. ask the producer to resumeProducing().
  1983. For L{IPullProducer} providers, C{resumeProducing} will be called once
  1984. each time data is required.
  1985. For L{IPushProducer} providers, C{pauseProducing} will be called
  1986. whenever the write buffer fills up and C{resumeProducing} will only be
  1987. called when it empties.
  1988. @type producer: L{IProducer} provider
  1989. @param producer: The L{IProducer} that will be producing data.
  1990. @type streaming: L{bool}
  1991. @param streaming: C{True} if C{producer} provides L{IPushProducer},
  1992. C{False} if C{producer} provides L{IPullProducer}.
  1993. @raise RuntimeError: If a producer is already registered.
  1994. @return: L{None}
  1995. """
  1996. if self._requestProducer is not None:
  1997. raise RuntimeError(
  1998. "Cannot register producer %s, because producer %s was never "
  1999. "unregistered." % (producer, self._requestProducer))
  2000. if not streaming:
  2001. producer = _PullToPush(producer, self)
  2002. self._requestProducer = producer
  2003. self._requestProducerStreaming = streaming
  2004. if not streaming:
  2005. producer.startStreaming()
  2006. def unregisterProducer(self):
  2007. """
  2008. Stop consuming data from a producer, without disconnecting.
  2009. @return: L{None}
  2010. """
  2011. if self._requestProducer is None:
  2012. return
  2013. if not self._requestProducerStreaming:
  2014. self._requestProducer.stopStreaming()
  2015. self._requestProducer = None
  2016. self._requestProducerStreaming = None
  2017. def stopProducing(self):
  2018. """
  2019. Stop producing data.
  2020. The HTTPChannel doesn't *actually* implement this, beacuse the
  2021. assumption is that it will only be called just before C{loseConnection}
  2022. is called. There's nothing sensible we can do other than call
  2023. C{loseConnection} anyway.
  2024. """
  2025. if self._requestProducer is not None:
  2026. self._requestProducer.stopProducing()
  2027. def pauseProducing(self):
  2028. """
  2029. Pause producing data.
  2030. This will be called by the transport when the send buffers have been
  2031. filled up. We want to simultaneously pause the producing L{Request}
  2032. object and also pause our transport.
  2033. The logic behind pausing the transport is specifically to avoid issues
  2034. like https://twistedmatrix.com/trac/ticket/8868. In this case, our
  2035. inability to send does not prevent us handling more requests, which
  2036. means we increasingly queue up more responses in our send buffer
  2037. without end. The easiest way to handle this is to ensure that if we are
  2038. unable to send our responses, we will not read further data from the
  2039. connection until the client pulls some data out. This is a bit of a
  2040. blunt instrument, but it's ok.
  2041. Note that this potentially interacts with timeout handling in a
  2042. positive way. Once the transport is paused the client may run into a
  2043. timeout which will cause us to tear the connection down. That's a good
  2044. thing!
  2045. """
  2046. self._waitingForTransport = True
  2047. # The first step is to tell any producer we might currently have
  2048. # registered to stop producing. If we can slow our applications down
  2049. # we should.
  2050. if self._requestProducer is not None:
  2051. self._requestProducer.pauseProducing()
  2052. # The next step here is to pause our own transport, as discussed in the
  2053. # docstring.
  2054. if not self._handlingRequest:
  2055. self._networkProducer.pauseProducing()
  2056. def resumeProducing(self):
  2057. """
  2058. Resume producing data.
  2059. This will be called by the transport when the send buffer has dropped
  2060. enough to actually send more data. When this happens we can unpause any
  2061. outstanding L{Request} producers we have, and also unpause our
  2062. transport.
  2063. """
  2064. self._waitingForTransport = False
  2065. if self._requestProducer is not None:
  2066. self._requestProducer.resumeProducing()
  2067. # We only want to resume the network producer if we're not currently
  2068. # waiting for a response to show up.
  2069. if not self._handlingRequest:
  2070. self._networkProducer.resumeProducing()
  2071. def _send100Continue(self):
  2072. """
  2073. Sends a 100 Continue response, used to signal to clients that further
  2074. processing will be performed.
  2075. """
  2076. self.transport.write(b"HTTP/1.1 100 Continue\r\n\r\n")
  2077. def _respondToBadRequestAndDisconnect(self):
  2078. """
  2079. This is a quick and dirty way of responding to bad requests.
  2080. As described by HTTP standard we should be patient and accept the
  2081. whole request from the client before sending a polite bad request
  2082. response, even in the case when clients send tons of data.
  2083. @param transport: Transport handling connection to the client.
  2084. @type transport: L{interfaces.ITransport}
  2085. """
  2086. self.transport.write(b"HTTP/1.1 400 Bad Request\r\n\r\n")
  2087. self.loseConnection()
  2088. def _escape(s):
  2089. """
  2090. Return a string like python repr, but always escaped as if surrounding
  2091. quotes were double quotes.
  2092. @param s: The string to escape.
  2093. @type s: L{bytes} or L{unicode}
  2094. @return: An escaped string.
  2095. @rtype: L{unicode}
  2096. """
  2097. if not isinstance(s, bytes):
  2098. s = s.encode("ascii")
  2099. r = repr(s)
  2100. if not isinstance(r, unicode):
  2101. r = r.decode("ascii")
  2102. if r.startswith(u"b"):
  2103. r = r[1:]
  2104. if r.startswith(u"'"):
  2105. return r[1:-1].replace(u'"', u'\\"').replace(u"\\'", u"'")
  2106. return r[1:-1]
  2107. @provider(IAccessLogFormatter)
  2108. def combinedLogFormatter(timestamp, request):
  2109. """
  2110. @return: A combined log formatted log line for the given request.
  2111. @see: L{IAccessLogFormatter}
  2112. """
  2113. clientAddr = request.getClientAddress()
  2114. if isinstance(clientAddr, (address.IPv4Address, address.IPv6Address,
  2115. _XForwardedForAddress)):
  2116. ip = clientAddr.host
  2117. else:
  2118. ip = b'-'
  2119. referrer = _escape(request.getHeader(b"referer") or b"-")
  2120. agent = _escape(request.getHeader(b"user-agent") or b"-")
  2121. line = (
  2122. u'"%(ip)s" - - %(timestamp)s "%(method)s %(uri)s %(protocol)s" '
  2123. u'%(code)d %(length)s "%(referrer)s" "%(agent)s"' % dict(
  2124. ip=_escape(ip),
  2125. timestamp=timestamp,
  2126. method=_escape(request.method),
  2127. uri=_escape(request.uri),
  2128. protocol=_escape(request.clientproto),
  2129. code=request.code,
  2130. length=request.sentLength or u"-",
  2131. referrer=referrer,
  2132. agent=agent,
  2133. ))
  2134. return line
  2135. @implementer(interfaces.IAddress)
  2136. class _XForwardedForAddress(object):
  2137. """
  2138. L{IAddress} which represents the client IP to log for a request, as gleaned
  2139. from an X-Forwarded-For header.
  2140. @ivar host: An IP address or C{b"-"}.
  2141. @type host: L{bytes}
  2142. @see: L{proxiedLogFormatter}
  2143. """
  2144. def __init__(self, host):
  2145. self.host = host
  2146. class _XForwardedForRequest(proxyForInterface(IRequest, "_request")):
  2147. """
  2148. Add a layer on top of another request that only uses the value of an
  2149. X-Forwarded-For header as the result of C{getClientAddress}.
  2150. """
  2151. def getClientAddress(self):
  2152. """
  2153. The client address (the first address) in the value of the
  2154. I{X-Forwarded-For header}. If the header is not present, the IP is
  2155. considered to be C{b"-"}.
  2156. @return: L{_XForwardedForAddress} which wraps the client address as
  2157. expected by L{combinedLogFormatter}.
  2158. """
  2159. host = self._request.requestHeaders.getRawHeaders(
  2160. b"x-forwarded-for", [b"-"])[0].split(b",")[0].strip()
  2161. return _XForwardedForAddress(host)
  2162. # These are missing from the interface. Forward them manually.
  2163. @property
  2164. def clientproto(self):
  2165. """
  2166. @return: The protocol version in the request.
  2167. @rtype: L{bytes}
  2168. """
  2169. return self._request.clientproto
  2170. @property
  2171. def code(self):
  2172. """
  2173. @return: The response code for the request.
  2174. @rtype: L{int}
  2175. """
  2176. return self._request.code
  2177. @property
  2178. def sentLength(self):
  2179. """
  2180. @return: The number of bytes sent in the response body.
  2181. @rtype: L{int}
  2182. """
  2183. return self._request.sentLength
  2184. @provider(IAccessLogFormatter)
  2185. def proxiedLogFormatter(timestamp, request):
  2186. """
  2187. @return: A combined log formatted log line for the given request but use
  2188. the value of the I{X-Forwarded-For} header as the value for the client
  2189. IP address.
  2190. @see: L{IAccessLogFormatter}
  2191. """
  2192. return combinedLogFormatter(timestamp, _XForwardedForRequest(request))
  2193. class _GenericHTTPChannelProtocol(proxyForInterface(IProtocol, "_channel")):
  2194. """
  2195. A proxy object that wraps one of the HTTP protocol objects, and switches
  2196. between them depending on TLS negotiated protocol.
  2197. @ivar _negotiatedProtocol: The protocol negotiated with ALPN or NPN, if
  2198. any.
  2199. @type _negotiatedProtocol: Either a bytestring containing the ALPN token
  2200. for the negotiated protocol, or L{None} if no protocol has yet been
  2201. negotiated.
  2202. @ivar _channel: The object capable of behaving like a L{HTTPChannel} that
  2203. is backing this object. By default this is a L{HTTPChannel}, but if a
  2204. HTTP protocol upgrade takes place this may be a different channel
  2205. object. Must implement L{IProtocol}.
  2206. @type _channel: L{HTTPChannel}
  2207. @ivar _requestFactory: A callable to use to build L{IRequest} objects.
  2208. @type _requestFactory: L{IRequest}
  2209. @ivar _site: A reference to the creating L{twisted.web.server.Site} object.
  2210. @type _site: L{twisted.web.server.Site}
  2211. @ivar _factory: A reference to the creating L{HTTPFactory} object.
  2212. @type _factory: L{HTTPFactory}
  2213. @ivar _timeOut: A timeout value to pass to the backing channel.
  2214. @type _timeOut: L{int} or L{None}
  2215. @ivar _callLater: A value for the C{callLater} callback.
  2216. @type _callLater: L{callable}
  2217. """
  2218. _negotiatedProtocol = None
  2219. _requestFactory = Request
  2220. _factory = None
  2221. _site = None
  2222. _timeOut = None
  2223. _callLater = None
  2224. @property
  2225. def factory(self):
  2226. """
  2227. @see: L{_genericHTTPChannelProtocolFactory}
  2228. """
  2229. return self._channel.factory
  2230. @factory.setter
  2231. def factory(self, value):
  2232. self._factory = value
  2233. self._channel.factory = value
  2234. @property
  2235. def requestFactory(self):
  2236. """
  2237. A callable to use to build L{IRequest} objects.
  2238. Retries the object from the current backing channel.
  2239. """
  2240. return self._channel.requestFactory
  2241. @requestFactory.setter
  2242. def requestFactory(self, value):
  2243. """
  2244. A callable to use to build L{IRequest} objects.
  2245. Sets the object on the backing channel and also stores the value for
  2246. propagation to any new channel.
  2247. @param value: The new callable to use.
  2248. @type value: A L{callable} returning L{IRequest}
  2249. """
  2250. self._requestFactory = value
  2251. self._channel.requestFactory = value
  2252. @property
  2253. def site(self):
  2254. """
  2255. A reference to the creating L{twisted.web.server.Site} object.
  2256. Returns the site object from the backing channel.
  2257. """
  2258. return self._channel.site
  2259. @site.setter
  2260. def site(self, value):
  2261. """
  2262. A reference to the creating L{twisted.web.server.Site} object.
  2263. Sets the object on the backing channel and also stores the value for
  2264. propagation to any new channel.
  2265. @param value: The L{twisted.web.server.Site} object to set.
  2266. @type value: L{twisted.web.server.Site}
  2267. """
  2268. self._site = value
  2269. self._channel.site = value
  2270. @property
  2271. def timeOut(self):
  2272. """
  2273. The idle timeout for the backing channel.
  2274. """
  2275. return self._channel.timeOut
  2276. @timeOut.setter
  2277. def timeOut(self, value):
  2278. """
  2279. The idle timeout for the backing channel.
  2280. Sets the idle timeout on both the backing channel and stores it for
  2281. propagation to any new backing channel.
  2282. @param value: The timeout to set.
  2283. @type value: L{int} or L{float}
  2284. """
  2285. self._timeOut = value
  2286. self._channel.timeOut = value
  2287. @property
  2288. def callLater(self):
  2289. """
  2290. A value for the C{callLater} callback. This callback is used by the
  2291. L{twisted.protocols.policies.TimeoutMixin} to handle timeouts.
  2292. """
  2293. return self._channel.callLater
  2294. @callLater.setter
  2295. def callLater(self, value):
  2296. """
  2297. Sets the value for the C{callLater} callback. This callback is used by
  2298. the L{twisted.protocols.policies.TimeoutMixin} to handle timeouts.
  2299. @param value: The new callback to use.
  2300. @type value: L{callable}
  2301. """
  2302. self._callLater = value
  2303. self._channel.callLater = value
  2304. def dataReceived(self, data):
  2305. """
  2306. An override of L{IProtocol.dataReceived} that checks what protocol we're
  2307. using.
  2308. """
  2309. if self._negotiatedProtocol is None:
  2310. try:
  2311. negotiatedProtocol = self._channel.transport.negotiatedProtocol
  2312. except AttributeError:
  2313. # Plaintext HTTP, always HTTP/1.1
  2314. negotiatedProtocol = b'http/1.1'
  2315. if negotiatedProtocol is None:
  2316. negotiatedProtocol = b'http/1.1'
  2317. if negotiatedProtocol == b'h2':
  2318. if not H2_ENABLED:
  2319. raise ValueError("Negotiated HTTP/2 without support.")
  2320. # We need to make sure that the HTTPChannel is unregistered
  2321. # from the transport so that the H2Connection can register
  2322. # itself if possible.
  2323. networkProducer = self._channel._networkProducer
  2324. networkProducer.unregisterProducer()
  2325. # Cancel the old channel's timeout.
  2326. self._channel.setTimeout(None)
  2327. # Cancel the old channel's timeout.
  2328. self._channel.setTimeout(None)
  2329. transport = self._channel.transport
  2330. self._channel = H2Connection()
  2331. self._channel.requestFactory = self._requestFactory
  2332. self._channel.site = self._site
  2333. self._channel.factory = self._factory
  2334. self._channel.timeOut = self._timeOut
  2335. self._channel.callLater = self._callLater
  2336. self._channel.makeConnection(transport)
  2337. # Register the H2Connection as the transport's
  2338. # producer, so that the transport can apply back
  2339. # pressure.
  2340. networkProducer.registerProducer(self._channel, True)
  2341. else:
  2342. # Only HTTP/2 and HTTP/1.1 are supported right now.
  2343. assert negotiatedProtocol == b'http/1.1', \
  2344. "Unsupported protocol negotiated"
  2345. self._negotiatedProtocol = negotiatedProtocol
  2346. return self._channel.dataReceived(data)
  2347. def _genericHTTPChannelProtocolFactory(self):
  2348. """
  2349. Returns an appropriately initialized _GenericHTTPChannelProtocol.
  2350. """
  2351. return _GenericHTTPChannelProtocol(HTTPChannel())
  2352. class HTTPFactory(protocol.ServerFactory):
  2353. """
  2354. Factory for HTTP server.
  2355. @ivar _logDateTime: A cached datetime string for log messages, updated by
  2356. C{_logDateTimeCall}.
  2357. @type _logDateTime: C{str}
  2358. @ivar _logDateTimeCall: A delayed call for the next update to the cached
  2359. log datetime string.
  2360. @type _logDateTimeCall: L{IDelayedCall} provided
  2361. @ivar _logFormatter: See the C{logFormatter} parameter to L{__init__}
  2362. @ivar _nativeize: A flag that indicates whether the log file being written
  2363. to wants native strings (C{True}) or bytes (C{False}). This is only to
  2364. support writing to L{twisted.python.log} which, unfortunately, works
  2365. with native strings.
  2366. @ivar _reactor: An L{IReactorTime} provider used to compute logging
  2367. timestamps.
  2368. """
  2369. protocol = _genericHTTPChannelProtocolFactory
  2370. logPath = None
  2371. timeOut = _REQUEST_TIMEOUT
  2372. def __init__(self, logPath=None, timeout=_REQUEST_TIMEOUT,
  2373. logFormatter=None, reactor=None):
  2374. """
  2375. @param logPath: File path to which access log messages will be written
  2376. or C{None} to disable logging.
  2377. @type logPath: L{str} or L{bytes}
  2378. @param timeout: The initial value of L{timeOut}, which defines the idle
  2379. connection timeout in seconds, or C{None} to disable the idle
  2380. timeout.
  2381. @type timeout: L{float}
  2382. @param logFormatter: An object to format requests into log lines for
  2383. the access log. L{combinedLogFormatter} when C{None} is passed.
  2384. @type logFormatter: L{IAccessLogFormatter} provider
  2385. @param reactor: A L{IReactorTime} provider used to manage connection
  2386. timeouts and compute logging timestamps.
  2387. """
  2388. if not reactor:
  2389. from twisted.internet import reactor
  2390. self._reactor = reactor
  2391. if logPath is not None:
  2392. logPath = os.path.abspath(logPath)
  2393. self.logPath = logPath
  2394. self.timeOut = timeout
  2395. if logFormatter is None:
  2396. logFormatter = combinedLogFormatter
  2397. self._logFormatter = logFormatter
  2398. # For storing the cached log datetime and the callback to update it
  2399. self._logDateTime = None
  2400. self._logDateTimeCall = None
  2401. def _updateLogDateTime(self):
  2402. """
  2403. Update log datetime periodically, so we aren't always recalculating it.
  2404. """
  2405. self._logDateTime = datetimeToLogString(self._reactor.seconds())
  2406. self._logDateTimeCall = self._reactor.callLater(1, self._updateLogDateTime)
  2407. def buildProtocol(self, addr):
  2408. p = protocol.ServerFactory.buildProtocol(self, addr)
  2409. # This is a bit of a hack to ensure that the HTTPChannel timeouts
  2410. # occur on the same reactor as the one we're using here. This could
  2411. # ideally be resolved by passing the reactor more generally to the
  2412. # HTTPChannel, but that won't work for the TimeoutMixin until we fix
  2413. # https://twistedmatrix.com/trac/ticket/8488
  2414. p.callLater = self._reactor.callLater
  2415. # timeOut needs to be on the Protocol instance cause
  2416. # TimeoutMixin expects it there
  2417. p.timeOut = self.timeOut
  2418. return p
  2419. def startFactory(self):
  2420. """
  2421. Set up request logging if necessary.
  2422. """
  2423. if self._logDateTimeCall is None:
  2424. self._updateLogDateTime()
  2425. if self.logPath:
  2426. self.logFile = self._openLogFile(self.logPath)
  2427. else:
  2428. self.logFile = log.logfile
  2429. def stopFactory(self):
  2430. if hasattr(self, "logFile"):
  2431. if self.logFile != log.logfile:
  2432. self.logFile.close()
  2433. del self.logFile
  2434. if self._logDateTimeCall is not None and self._logDateTimeCall.active():
  2435. self._logDateTimeCall.cancel()
  2436. self._logDateTimeCall = None
  2437. def _openLogFile(self, path):
  2438. """
  2439. Override in subclasses, e.g. to use L{twisted.python.logfile}.
  2440. """
  2441. f = open(path, "ab", 1)
  2442. return f
  2443. def log(self, request):
  2444. """
  2445. Write a line representing C{request} to the access log file.
  2446. @param request: The request object about which to log.
  2447. @type request: L{Request}
  2448. """
  2449. try:
  2450. logFile = self.logFile
  2451. except AttributeError:
  2452. pass
  2453. else:
  2454. line = self._logFormatter(self._logDateTime, request) + u"\n"
  2455. logFile.write(line.encode('utf8'))