http.py 103 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170
  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. clength = self.content.tell()
  678. self.content.seek(0, 0)
  679. self.args = {}
  680. self.method, self.uri = command, path
  681. self.clientproto = version
  682. x = self.uri.split(b'?', 1)
  683. if len(x) == 1:
  684. self.path = self.uri
  685. else:
  686. self.path, argstring = x
  687. self.args = parse_qs(argstring, 1)
  688. # Argument processing
  689. args = self.args
  690. ctype = self.requestHeaders.getRawHeaders(b'content-type')
  691. if ctype is not None:
  692. ctype = ctype[0]
  693. if self.method == b"POST" and ctype and clength:
  694. mfd = b'multipart/form-data'
  695. key, pdict = _parseHeader(ctype)
  696. # This weird CONTENT-LENGTH param is required by
  697. # cgi.parse_multipart() in some versions of Python 3.7+, see
  698. # bpo-29979. It looks like this will be relaxed and backported, see
  699. # https://github.com/python/cpython/pull/8530.
  700. pdict["CONTENT-LENGTH"] = clength
  701. if key == b'application/x-www-form-urlencoded':
  702. args.update(parse_qs(self.content.read(), 1))
  703. elif key == mfd:
  704. try:
  705. if _PY37PLUS:
  706. cgiArgs = cgi.parse_multipart(
  707. self.content, pdict, encoding='utf8',
  708. errors="surrogateescape")
  709. else:
  710. cgiArgs = cgi.parse_multipart(self.content, pdict)
  711. if not _PY37PLUS and _PY3:
  712. # The parse_multipart function on Python 3
  713. # decodes the header bytes as iso-8859-1 and
  714. # returns a str key -- we want bytes so encode
  715. # it back
  716. self.args.update({x.encode('iso-8859-1'): y
  717. for x, y in cgiArgs.items()})
  718. elif _PY37PLUS:
  719. # The parse_multipart function on Python 3.7+
  720. # decodes the header bytes as iso-8859-1 and
  721. # decodes the body bytes as utf8 with
  722. # surrogateescape -- we want bytes
  723. self.args.update({
  724. x.encode('iso-8859-1'): \
  725. [z.encode('utf8', "surrogateescape")
  726. if isinstance(z, str) else z for z in y]
  727. for x, y in cgiArgs.items()})
  728. else:
  729. self.args.update(cgiArgs)
  730. except Exception as e:
  731. # It was a bad request, or we got a signal.
  732. self.channel._respondToBadRequestAndDisconnect()
  733. if isinstance(e, (TypeError, ValueError, KeyError)):
  734. return
  735. else:
  736. # If it's not a userspace error from CGI, reraise
  737. raise
  738. self.content.seek(0, 0)
  739. self.process()
  740. def __repr__(self):
  741. """
  742. Return a string description of the request including such information
  743. as the request method and request URI.
  744. @return: A string loosely describing this L{Request} object.
  745. @rtype: L{str}
  746. """
  747. return '<%s at 0x%x method=%s uri=%s clientproto=%s>' % (
  748. self.__class__.__name__,
  749. id(self),
  750. nativeString(self.method),
  751. nativeString(self.uri),
  752. nativeString(self.clientproto))
  753. def process(self):
  754. """
  755. Override in subclasses.
  756. This method is not intended for users.
  757. """
  758. pass
  759. # consumer interface
  760. def registerProducer(self, producer, streaming):
  761. """
  762. Register a producer.
  763. """
  764. if self.producer:
  765. raise ValueError(
  766. "registering producer %s before previous one (%s) was "
  767. "unregistered" % (producer, self.producer))
  768. self.streamingProducer = streaming
  769. self.producer = producer
  770. self.channel.registerProducer(producer, streaming)
  771. def unregisterProducer(self):
  772. """
  773. Unregister the producer.
  774. """
  775. self.channel.unregisterProducer()
  776. self.producer = None
  777. # The following is the public interface that people should be
  778. # writing to.
  779. def getHeader(self, key):
  780. """
  781. Get an HTTP request header.
  782. @type key: C{bytes} or C{str}
  783. @param key: The name of the header to get the value of.
  784. @rtype: C{bytes} or C{str} or L{None}
  785. @return: The value of the specified header, or L{None} if that header
  786. was not present in the request. The string type of the result
  787. matches the type of L{key}.
  788. """
  789. value = self.requestHeaders.getRawHeaders(key)
  790. if value is not None:
  791. return value[-1]
  792. def getCookie(self, key):
  793. """
  794. Get a cookie that was sent from the network.
  795. @type key: C{bytes}
  796. @param key: The name of the cookie to get.
  797. @rtype: C{bytes} or C{None}
  798. @returns: The value of the specified cookie, or L{None} if that cookie
  799. was not present in the request.
  800. """
  801. return self.received_cookies.get(key)
  802. def notifyFinish(self):
  803. """
  804. Notify when the response to this request has finished.
  805. @note: There are some caveats around the reliability of the delivery of
  806. this notification.
  807. 1. If this L{Request}'s channel is paused, the notification
  808. will not be delivered. This can happen in one of two ways;
  809. either you can call C{request.transport.pauseProducing}
  810. yourself, or,
  811. 2. In order to deliver this notification promptly when a client
  812. disconnects, the reactor must continue reading from the
  813. transport, so that it can tell when the underlying network
  814. connection has gone away. Twisted Web will only keep
  815. reading up until a finite (small) maximum buffer size before
  816. it gives up and pauses the transport itself. If this
  817. occurs, you will not discover that the connection has gone
  818. away until a timeout fires or until the application attempts
  819. to send some data via L{Request.write}.
  820. 3. It is theoretically impossible to distinguish between
  821. successfully I{sending} a response and the peer successfully
  822. I{receiving} it. There are several networking edge cases
  823. where the L{Deferred}s returned by C{notifyFinish} will
  824. indicate success, but the data will never be received.
  825. There are also edge cases where the connection will appear
  826. to fail, but in reality the response was delivered. As a
  827. result, the information provided by the result of the
  828. L{Deferred}s returned by this method should be treated as a
  829. guess; do not make critical decisions in your applications
  830. based upon it.
  831. @rtype: L{Deferred}
  832. @return: A L{Deferred} which will be triggered when the request is
  833. finished -- with a L{None} value if the request finishes
  834. successfully or with an error if the request is interrupted by an
  835. error (for example, the client closing the connection prematurely).
  836. """
  837. self.notifications.append(Deferred())
  838. return self.notifications[-1]
  839. def finish(self):
  840. """
  841. Indicate that all response data has been written to this L{Request}.
  842. """
  843. if self._disconnected:
  844. raise RuntimeError(
  845. "Request.finish called on a request after its connection was lost; "
  846. "use Request.notifyFinish to keep track of this.")
  847. if self.finished:
  848. warnings.warn("Warning! request.finish called twice.", stacklevel=2)
  849. return
  850. if not self.startedWriting:
  851. # write headers
  852. self.write(b'')
  853. if self.chunked:
  854. # write last chunk and closing CRLF
  855. self.channel.write(b"0\r\n\r\n")
  856. # log request
  857. if (hasattr(self.channel, "factory") and
  858. self.channel.factory is not None):
  859. self.channel.factory.log(self)
  860. self.finished = 1
  861. if not self.queued:
  862. self._cleanup()
  863. def write(self, data):
  864. """
  865. Write some data as a result of an HTTP request. The first
  866. time this is called, it writes out response data.
  867. @type data: C{bytes}
  868. @param data: Some bytes to be sent as part of the response body.
  869. """
  870. if self.finished:
  871. raise RuntimeError('Request.write called on a request after '
  872. 'Request.finish was called.')
  873. if self._disconnected:
  874. # Don't attempt to write any data to a disconnected client.
  875. # The RuntimeError exception will be thrown as usual when
  876. # request.finish is called
  877. return
  878. if not self.startedWriting:
  879. self.startedWriting = 1
  880. version = self.clientproto
  881. code = intToBytes(self.code)
  882. reason = self.code_message
  883. headers = []
  884. # if we don't have a content length, we send data in
  885. # chunked mode, so that we can support pipelining in
  886. # persistent connections.
  887. if ((version == b"HTTP/1.1") and
  888. (self.responseHeaders.getRawHeaders(b'content-length') is None) and
  889. self.method != b"HEAD" and self.code not in NO_BODY_CODES):
  890. headers.append((b'Transfer-Encoding', b'chunked'))
  891. self.chunked = 1
  892. if self.lastModified is not None:
  893. if self.responseHeaders.hasHeader(b'last-modified'):
  894. self._log.info(
  895. "Warning: last-modified specified both in"
  896. " header list and lastModified attribute."
  897. )
  898. else:
  899. self.responseHeaders.setRawHeaders(
  900. b'last-modified',
  901. [datetimeToString(self.lastModified)])
  902. if self.etag is not None:
  903. self.responseHeaders.setRawHeaders(b'ETag', [self.etag])
  904. for name, values in self.responseHeaders.getAllRawHeaders():
  905. for value in values:
  906. headers.append((name, value))
  907. for cookie in self.cookies:
  908. headers.append((b'Set-Cookie', cookie))
  909. self.channel.writeHeaders(version, code, reason, headers)
  910. # if this is a "HEAD" request, we shouldn't return any data
  911. if self.method == b"HEAD":
  912. self.write = lambda data: None
  913. return
  914. # for certain result codes, we should never return any data
  915. if self.code in NO_BODY_CODES:
  916. self.write = lambda data: None
  917. return
  918. self.sentLength = self.sentLength + len(data)
  919. if data:
  920. if self.chunked:
  921. self.channel.writeSequence(toChunk(data))
  922. else:
  923. self.channel.write(data)
  924. def addCookie(self, k, v, expires=None, domain=None, path=None,
  925. max_age=None, comment=None, secure=None, httpOnly=False,
  926. sameSite=None):
  927. """
  928. Set an outgoing HTTP cookie.
  929. In general, you should consider using sessions instead of cookies, see
  930. L{twisted.web.server.Request.getSession} and the
  931. L{twisted.web.server.Session} class for details.
  932. @param k: cookie name
  933. @type k: L{bytes} or L{unicode}
  934. @param v: cookie value
  935. @type v: L{bytes} or L{unicode}
  936. @param expires: cookie expire attribute value in
  937. "Wdy, DD Mon YYYY HH:MM:SS GMT" format
  938. @type expires: L{bytes} or L{unicode}
  939. @param domain: cookie domain
  940. @type domain: L{bytes} or L{unicode}
  941. @param path: cookie path
  942. @type path: L{bytes} or L{unicode}
  943. @param max_age: cookie expiration in seconds from reception
  944. @type max_age: L{bytes} or L{unicode}
  945. @param comment: cookie comment
  946. @type comment: L{bytes} or L{unicode}
  947. @param secure: direct browser to send the cookie on encrypted
  948. connections only
  949. @type secure: L{bool}
  950. @param httpOnly: direct browser not to expose cookies through channels
  951. other than HTTP (and HTTPS) requests
  952. @type httpOnly: L{bool}
  953. @param sameSite: One of L{None} (default), C{'lax'} or C{'strict'}.
  954. Direct browsers not to send this cookie on cross-origin requests.
  955. Please see:
  956. U{https://tools.ietf.org/html/draft-west-first-party-cookies-07}
  957. @type sameSite: L{None}, L{bytes} or L{unicode}
  958. @raises: L{DeprecationWarning} if an argument is not L{bytes} or
  959. L{unicode}.
  960. L{ValueError} if the value for C{sameSite} is not supported.
  961. """
  962. def _ensureBytes(val):
  963. """
  964. Ensure that C{val} is bytes, encoding using UTF-8 if
  965. needed.
  966. @param val: L{bytes} or L{unicode}
  967. @return: L{bytes}
  968. """
  969. if val is None:
  970. # It's None, so we don't want to touch it
  971. return val
  972. if isinstance(val, bytes):
  973. return val
  974. else:
  975. return val.encode('utf8')
  976. def _sanitize(val):
  977. """
  978. Replace linear whitespace (C{\r}, C{\n}, C{\r\n}) and
  979. semicolons C{;} in C{val} with a single space.
  980. @param val: L{bytes}
  981. @return: L{bytes}
  982. """
  983. return _sanitizeLinearWhitespace(val).replace(b';', b' ')
  984. cookie = (
  985. _sanitize(_ensureBytes(k)) +
  986. b"=" +
  987. _sanitize(_ensureBytes(v)))
  988. if expires is not None:
  989. cookie = cookie + b"; Expires=" + _sanitize(_ensureBytes(expires))
  990. if domain is not None:
  991. cookie = cookie + b"; Domain=" + _sanitize(_ensureBytes(domain))
  992. if path is not None:
  993. cookie = cookie + b"; Path=" + _sanitize(_ensureBytes(path))
  994. if max_age is not None:
  995. cookie = cookie + b"; Max-Age=" + _sanitize(_ensureBytes(max_age))
  996. if comment is not None:
  997. cookie = cookie + b"; Comment=" + _sanitize(_ensureBytes(comment))
  998. if secure:
  999. cookie = cookie + b"; Secure"
  1000. if httpOnly:
  1001. cookie = cookie + b"; HttpOnly"
  1002. if sameSite:
  1003. sameSite = _ensureBytes(sameSite).lower()
  1004. if sameSite not in [b"lax", b"strict"]:
  1005. raise ValueError(
  1006. "Invalid value for sameSite: " + repr(sameSite))
  1007. cookie += b"; SameSite=" + sameSite
  1008. self.cookies.append(cookie)
  1009. def setResponseCode(self, code, message=None):
  1010. """
  1011. Set the HTTP response code.
  1012. @type code: L{int}
  1013. @type message: L{bytes}
  1014. """
  1015. if not isinstance(code, _intTypes):
  1016. raise TypeError("HTTP response code must be int or long")
  1017. self.code = code
  1018. if message:
  1019. if not isinstance(message, bytes):
  1020. raise TypeError("HTTP response status message must be bytes")
  1021. self.code_message = message
  1022. else:
  1023. self.code_message = RESPONSES.get(code, b"Unknown Status")
  1024. def setHeader(self, name, value):
  1025. """
  1026. Set an HTTP response header. Overrides any previously set values for
  1027. this header.
  1028. @type k: L{bytes} or L{str}
  1029. @param k: The name of the header for which to set the value.
  1030. @type v: L{bytes} or L{str}
  1031. @param v: The value to set for the named header. A L{str} will be
  1032. UTF-8 encoded, which may not interoperable with other
  1033. implementations. Avoid passing non-ASCII characters if possible.
  1034. """
  1035. self.responseHeaders.setRawHeaders(name, [value])
  1036. def redirect(self, url):
  1037. """
  1038. Utility function that does a redirect.
  1039. Set the response code to L{FOUND} and the I{Location} header to the
  1040. given URL.
  1041. The request should have C{finish()} called after this.
  1042. @param url: I{Location} header value.
  1043. @type url: L{bytes} or L{str}
  1044. """
  1045. self.setResponseCode(FOUND)
  1046. self.setHeader(b"location", url)
  1047. def setLastModified(self, when):
  1048. """
  1049. Set the C{Last-Modified} time for the response to this request.
  1050. If I am called more than once, I ignore attempts to set
  1051. Last-Modified earlier, only replacing the Last-Modified time
  1052. if it is to a later value.
  1053. If I am a conditional request, I may modify my response code
  1054. to L{NOT_MODIFIED} if appropriate for the time given.
  1055. @param when: The last time the resource being returned was
  1056. modified, in seconds since the epoch.
  1057. @type when: number
  1058. @return: If I am a I{If-Modified-Since} conditional request and
  1059. the time given is not newer than the condition, I return
  1060. L{http.CACHED<CACHED>} to indicate that you should write no
  1061. body. Otherwise, I return a false value.
  1062. """
  1063. # time.time() may be a float, but the HTTP-date strings are
  1064. # only good for whole seconds.
  1065. when = int(math.ceil(when))
  1066. if (not self.lastModified) or (self.lastModified < when):
  1067. self.lastModified = when
  1068. modifiedSince = self.getHeader(b'if-modified-since')
  1069. if modifiedSince:
  1070. firstPart = modifiedSince.split(b';', 1)[0]
  1071. try:
  1072. modifiedSince = stringToDatetime(firstPart)
  1073. except ValueError:
  1074. return None
  1075. if modifiedSince >= self.lastModified:
  1076. self.setResponseCode(NOT_MODIFIED)
  1077. return CACHED
  1078. return None
  1079. def setETag(self, etag):
  1080. """
  1081. Set an C{entity tag} for the outgoing response.
  1082. That's \"entity tag\" as in the HTTP/1.1 C{ETag} header, \"used
  1083. for comparing two or more entities from the same requested
  1084. resource.\"
  1085. If I am a conditional request, I may modify my response code
  1086. to L{NOT_MODIFIED} or L{PRECONDITION_FAILED}, if appropriate
  1087. for the tag given.
  1088. @param etag: The entity tag for the resource being returned.
  1089. @type etag: string
  1090. @return: If I am a C{If-None-Match} conditional request and
  1091. the tag matches one in the request, I return
  1092. L{http.CACHED<CACHED>} to indicate that you should write
  1093. no body. Otherwise, I return a false value.
  1094. """
  1095. if etag:
  1096. self.etag = etag
  1097. tags = self.getHeader(b"if-none-match")
  1098. if tags:
  1099. tags = tags.split()
  1100. if (etag in tags) or (b'*' in tags):
  1101. self.setResponseCode(((self.method in (b"HEAD", b"GET"))
  1102. and NOT_MODIFIED)
  1103. or PRECONDITION_FAILED)
  1104. return CACHED
  1105. return None
  1106. def getAllHeaders(self):
  1107. """
  1108. Return dictionary mapping the names of all received headers to the last
  1109. value received for each.
  1110. Since this method does not return all header information,
  1111. C{self.requestHeaders.getAllRawHeaders()} may be preferred.
  1112. """
  1113. headers = {}
  1114. for k, v in self.requestHeaders.getAllRawHeaders():
  1115. headers[k.lower()] = v[-1]
  1116. return headers
  1117. def getRequestHostname(self):
  1118. """
  1119. Get the hostname that the user passed in to the request.
  1120. This will either use the Host: header (if it is available) or the
  1121. host we are listening on if the header is unavailable.
  1122. @returns: the requested hostname
  1123. @rtype: C{bytes}
  1124. """
  1125. # XXX This method probably has no unit tests. I changed it a ton and
  1126. # nothing failed.
  1127. host = self.getHeader(b'host')
  1128. if host:
  1129. return host.split(b':', 1)[0]
  1130. return networkString(self.getHost().host)
  1131. def getHost(self):
  1132. """
  1133. Get my originally requesting transport's host.
  1134. Don't rely on the 'transport' attribute, since Request objects may be
  1135. copied remotely. For information on this method's return value, see
  1136. L{twisted.internet.tcp.Port}.
  1137. """
  1138. return self.host
  1139. def setHost(self, host, port, ssl=0):
  1140. """
  1141. Change the host and port the request thinks it's using.
  1142. This method is useful for working with reverse HTTP proxies (e.g.
  1143. both Squid and Apache's mod_proxy can do this), when the address
  1144. the HTTP client is using is different than the one we're listening on.
  1145. For example, Apache may be listening on https://www.example.com/, and
  1146. then forwarding requests to http://localhost:8080/, but we don't want
  1147. HTML produced by Twisted to say b'http://localhost:8080/', they should
  1148. say b'https://www.example.com/', so we do::
  1149. request.setHost(b'www.example.com', 443, ssl=1)
  1150. @type host: C{bytes}
  1151. @param host: The value to which to change the host header.
  1152. @type ssl: C{bool}
  1153. @param ssl: A flag which, if C{True}, indicates that the request is
  1154. considered secure (if C{True}, L{isSecure} will return C{True}).
  1155. """
  1156. self._forceSSL = ssl # set first so isSecure will work
  1157. if self.isSecure():
  1158. default = 443
  1159. else:
  1160. default = 80
  1161. if port == default:
  1162. hostHeader = host
  1163. else:
  1164. hostHeader = host + b":" + intToBytes(port)
  1165. self.requestHeaders.setRawHeaders(b"host", [hostHeader])
  1166. self.host = address.IPv4Address("TCP", host, port)
  1167. def getClientIP(self):
  1168. """
  1169. Return the IP address of the client who submitted this request.
  1170. This method is B{deprecated}. Use L{getClientAddress} instead.
  1171. @returns: the client IP address
  1172. @rtype: C{str}
  1173. """
  1174. if isinstance(self.client, (address.IPv4Address, address.IPv6Address)):
  1175. return self.client.host
  1176. else:
  1177. return None
  1178. def getClientAddress(self):
  1179. """
  1180. Return the address of the client who submitted this request.
  1181. This may not be a network address (e.g., a server listening on
  1182. a UNIX domain socket will cause this to return
  1183. L{UNIXAddress}). Callers must check the type of the returned
  1184. address.
  1185. @since: 18.4
  1186. @return: the client's address.
  1187. @rtype: L{IAddress}
  1188. """
  1189. return self.client
  1190. def isSecure(self):
  1191. """
  1192. Return L{True} if this request is using a secure transport.
  1193. Normally this method returns L{True} if this request's L{HTTPChannel}
  1194. instance is using a transport that implements
  1195. L{interfaces.ISSLTransport}.
  1196. This will also return L{True} if L{Request.setHost} has been called
  1197. with C{ssl=True}.
  1198. @returns: L{True} if this request is secure
  1199. @rtype: C{bool}
  1200. """
  1201. if self._forceSSL:
  1202. return True
  1203. channel = getattr(self, 'channel', None)
  1204. if channel is None:
  1205. return False
  1206. return channel.isSecure()
  1207. def _authorize(self):
  1208. # Authorization, (mostly) per the RFC
  1209. try:
  1210. authh = self.getHeader(b"Authorization")
  1211. if not authh:
  1212. self.user = self.password = b''
  1213. return
  1214. bas, upw = authh.split()
  1215. if bas.lower() != b"basic":
  1216. raise ValueError()
  1217. upw = base64.decodestring(upw)
  1218. self.user, self.password = upw.split(b':', 1)
  1219. except (binascii.Error, ValueError):
  1220. self.user = self.password = b''
  1221. except:
  1222. self._log.failure('')
  1223. self.user = self.password = b''
  1224. def getUser(self):
  1225. """
  1226. Return the HTTP user sent with this request, if any.
  1227. If no user was supplied, return the empty string.
  1228. @returns: the HTTP user, if any
  1229. @rtype: C{bytes}
  1230. """
  1231. try:
  1232. return self.user
  1233. except:
  1234. pass
  1235. self._authorize()
  1236. return self.user
  1237. def getPassword(self):
  1238. """
  1239. Return the HTTP password sent with this request, if any.
  1240. If no password was supplied, return the empty string.
  1241. @returns: the HTTP password, if any
  1242. @rtype: C{bytes}
  1243. """
  1244. try:
  1245. return self.password
  1246. except:
  1247. pass
  1248. self._authorize()
  1249. return self.password
  1250. def connectionLost(self, reason):
  1251. """
  1252. There is no longer a connection for this request to respond over.
  1253. Clean up anything which can't be useful anymore.
  1254. """
  1255. self._disconnected = True
  1256. self.channel = None
  1257. if self.content is not None:
  1258. self.content.close()
  1259. for d in self.notifications:
  1260. d.errback(reason)
  1261. self.notifications = []
  1262. def loseConnection(self):
  1263. """
  1264. Pass the loseConnection through to the underlying channel.
  1265. """
  1266. if self.channel is not None:
  1267. self.channel.loseConnection()
  1268. def __eq__(self, other):
  1269. """
  1270. Determines if two requests are the same object.
  1271. @param other: Another object whose identity will be compared
  1272. to this instance's.
  1273. @return: L{True} when the two are the same object and L{False}
  1274. when not.
  1275. @rtype: L{bool}
  1276. """
  1277. # When other is not an instance of request, return
  1278. # NotImplemented so that Python uses other.__eq__ to perform
  1279. # the comparison. This ensures that a Request proxy generated
  1280. # by proxyForInterface compares equal to an actual Request
  1281. # instanceby turning request != proxy into proxy != request.
  1282. if isinstance(other, Request):
  1283. return self is other
  1284. return NotImplemented
  1285. def __ne__(self, other):
  1286. """
  1287. Determines if two requests are not the same object.
  1288. @param other: Another object whose identity will be compared
  1289. to this instance's.
  1290. @return: L{True} when the two are not the same object and
  1291. L{False} when they are.
  1292. @rtype: L{bool}
  1293. """
  1294. # When other is not an instance of request, return
  1295. # NotImplemented so that Python uses other.__ne__ to perform
  1296. # the comparison. This ensures that a Request proxy generated
  1297. # by proxyForInterface can compare equal to an actual Request
  1298. # instance by turning request != proxy into proxy != request.
  1299. if isinstance(other, Request):
  1300. return self is not other
  1301. return NotImplemented
  1302. def __hash__(self):
  1303. """
  1304. A C{Request} is hashable so that it can be used as a mapping key.
  1305. @return: A C{int} based on the instance's identity.
  1306. """
  1307. return id(self)
  1308. Request.getClientIP = deprecated(
  1309. Version('Twisted', 18, 4, 0),
  1310. replacement="getClientAddress",
  1311. )(Request.getClientIP)
  1312. Request.noLongerQueued = deprecated(
  1313. Version("Twisted", 16, 3, 0))(Request.noLongerQueued)
  1314. class _DataLoss(Exception):
  1315. """
  1316. L{_DataLoss} indicates that not all of a message body was received. This
  1317. is only one of several possible exceptions which may indicate that data
  1318. was lost. Because of this, it should not be checked for by
  1319. specifically; any unexpected exception should be treated as having
  1320. caused data loss.
  1321. """
  1322. class PotentialDataLoss(Exception):
  1323. """
  1324. L{PotentialDataLoss} may be raised by a transfer encoding decoder's
  1325. C{noMoreData} method to indicate that it cannot be determined if the
  1326. entire response body has been delivered. This only occurs when making
  1327. requests to HTTP servers which do not set I{Content-Length} or a
  1328. I{Transfer-Encoding} in the response because in this case the end of the
  1329. response is indicated by the connection being closed, an event which may
  1330. also be due to a transient network problem or other error.
  1331. """
  1332. class _MalformedChunkedDataError(Exception):
  1333. """
  1334. C{_ChunkedTranferDecoder} raises L{_MalformedChunkedDataError} from its
  1335. C{dataReceived} method when it encounters malformed data. This exception
  1336. indicates a client-side error. If this exception is raised, the connection
  1337. should be dropped with a 400 error.
  1338. """
  1339. class _IdentityTransferDecoder(object):
  1340. """
  1341. Protocol for accumulating bytes up to a specified length. This handles the
  1342. case where no I{Transfer-Encoding} is specified.
  1343. @ivar contentLength: Counter keeping track of how many more bytes there are
  1344. to receive.
  1345. @ivar dataCallback: A one-argument callable which will be invoked each
  1346. time application data is received.
  1347. @ivar finishCallback: A one-argument callable which will be invoked when
  1348. the terminal chunk is received. It will be invoked with all bytes
  1349. which were delivered to this protocol which came after the terminal
  1350. chunk.
  1351. """
  1352. def __init__(self, contentLength, dataCallback, finishCallback):
  1353. self.contentLength = contentLength
  1354. self.dataCallback = dataCallback
  1355. self.finishCallback = finishCallback
  1356. def dataReceived(self, data):
  1357. """
  1358. Interpret the next chunk of bytes received. Either deliver them to the
  1359. data callback or invoke the finish callback if enough bytes have been
  1360. received.
  1361. @raise RuntimeError: If the finish callback has already been invoked
  1362. during a previous call to this methood.
  1363. """
  1364. if self.dataCallback is None:
  1365. raise RuntimeError(
  1366. "_IdentityTransferDecoder cannot decode data after finishing")
  1367. if self.contentLength is None:
  1368. self.dataCallback(data)
  1369. elif len(data) < self.contentLength:
  1370. self.contentLength -= len(data)
  1371. self.dataCallback(data)
  1372. else:
  1373. # Make the state consistent before invoking any code belonging to
  1374. # anyone else in case noMoreData ends up being called beneath this
  1375. # stack frame.
  1376. contentLength = self.contentLength
  1377. dataCallback = self.dataCallback
  1378. finishCallback = self.finishCallback
  1379. self.dataCallback = self.finishCallback = None
  1380. self.contentLength = 0
  1381. dataCallback(data[:contentLength])
  1382. finishCallback(data[contentLength:])
  1383. def noMoreData(self):
  1384. """
  1385. All data which will be delivered to this decoder has been. Check to
  1386. make sure as much data as was expected has been received.
  1387. @raise PotentialDataLoss: If the content length is unknown.
  1388. @raise _DataLoss: If the content length is known and fewer than that
  1389. many bytes have been delivered.
  1390. @return: L{None}
  1391. """
  1392. finishCallback = self.finishCallback
  1393. self.dataCallback = self.finishCallback = None
  1394. if self.contentLength is None:
  1395. finishCallback(b'')
  1396. raise PotentialDataLoss()
  1397. elif self.contentLength != 0:
  1398. raise _DataLoss()
  1399. class _ChunkedTransferDecoder(object):
  1400. """
  1401. Protocol for decoding I{chunked} Transfer-Encoding, as defined by RFC 2616,
  1402. section 3.6.1. This protocol can interpret the contents of a request or
  1403. response body which uses the I{chunked} Transfer-Encoding. It cannot
  1404. interpret any of the rest of the HTTP protocol.
  1405. It may make sense for _ChunkedTransferDecoder to be an actual IProtocol
  1406. implementation. Currently, the only user of this class will only ever
  1407. call dataReceived on it. However, it might be an improvement if the
  1408. user could connect this to a transport and deliver connection lost
  1409. notification. This way, `dataCallback` becomes `self.transport.write`
  1410. and perhaps `finishCallback` becomes `self.transport.loseConnection()`
  1411. (although I'm not sure where the extra data goes in that case). This
  1412. could also allow this object to indicate to the receiver of data that
  1413. the stream was not completely received, an error case which should be
  1414. noticed. -exarkun
  1415. @ivar dataCallback: A one-argument callable which will be invoked each
  1416. time application data is received.
  1417. @ivar finishCallback: A one-argument callable which will be invoked when
  1418. the terminal chunk is received. It will be invoked with all bytes
  1419. which were delivered to this protocol which came after the terminal
  1420. chunk.
  1421. @ivar length: Counter keeping track of how many more bytes in a chunk there
  1422. are to receive.
  1423. @ivar state: One of C{'CHUNK_LENGTH'}, C{'CRLF'}, C{'TRAILER'},
  1424. C{'BODY'}, or C{'FINISHED'}. For C{'CHUNK_LENGTH'}, data for the
  1425. chunk length line is currently being read. For C{'CRLF'}, the CR LF
  1426. pair which follows each chunk is being read. For C{'TRAILER'}, the CR
  1427. LF pair which follows the terminal 0-length chunk is currently being
  1428. read. For C{'BODY'}, the contents of a chunk are being read. For
  1429. C{'FINISHED'}, the last chunk has been completely read and no more
  1430. input is valid.
  1431. """
  1432. state = 'CHUNK_LENGTH'
  1433. def __init__(self, dataCallback, finishCallback):
  1434. self.dataCallback = dataCallback
  1435. self.finishCallback = finishCallback
  1436. self._buffer = b''
  1437. def _dataReceived_CHUNK_LENGTH(self, data):
  1438. if b'\r\n' in data:
  1439. line, rest = data.split(b'\r\n', 1)
  1440. parts = line.split(b';')
  1441. try:
  1442. self.length = int(parts[0], 16)
  1443. except ValueError:
  1444. raise _MalformedChunkedDataError(
  1445. "Chunk-size must be an integer.")
  1446. if self.length == 0:
  1447. self.state = 'TRAILER'
  1448. else:
  1449. self.state = 'BODY'
  1450. return rest
  1451. else:
  1452. self._buffer = data
  1453. return b''
  1454. def _dataReceived_CRLF(self, data):
  1455. if data.startswith(b'\r\n'):
  1456. self.state = 'CHUNK_LENGTH'
  1457. return data[2:]
  1458. else:
  1459. self._buffer = data
  1460. return b''
  1461. def _dataReceived_TRAILER(self, data):
  1462. if data.startswith(b'\r\n'):
  1463. data = data[2:]
  1464. self.state = 'FINISHED'
  1465. self.finishCallback(data)
  1466. else:
  1467. self._buffer = data
  1468. return b''
  1469. def _dataReceived_BODY(self, data):
  1470. if len(data) >= self.length:
  1471. chunk, data = data[:self.length], data[self.length:]
  1472. self.dataCallback(chunk)
  1473. self.state = 'CRLF'
  1474. return data
  1475. elif len(data) < self.length:
  1476. self.length -= len(data)
  1477. self.dataCallback(data)
  1478. return b''
  1479. def _dataReceived_FINISHED(self, data):
  1480. raise RuntimeError(
  1481. "_ChunkedTransferDecoder.dataReceived called after last "
  1482. "chunk was processed")
  1483. def dataReceived(self, data):
  1484. """
  1485. Interpret data from a request or response body which uses the
  1486. I{chunked} Transfer-Encoding.
  1487. """
  1488. data = self._buffer + data
  1489. self._buffer = b''
  1490. while data:
  1491. data = getattr(self, '_dataReceived_%s' % (self.state,))(data)
  1492. def noMoreData(self):
  1493. """
  1494. Verify that all data has been received. If it has not been, raise
  1495. L{_DataLoss}.
  1496. """
  1497. if self.state != 'FINISHED':
  1498. raise _DataLoss(
  1499. "Chunked decoder in %r state, still expecting more data to "
  1500. "get to 'FINISHED' state." % (self.state,))
  1501. @implementer(interfaces.IPushProducer)
  1502. class _NoPushProducer(object):
  1503. """
  1504. A no-op version of L{interfaces.IPushProducer}, used to abstract over the
  1505. possibility that a L{HTTPChannel} transport does not provide
  1506. L{IPushProducer}.
  1507. """
  1508. def pauseProducing(self):
  1509. """
  1510. Pause producing data.
  1511. Tells a producer that it has produced too much data to process for
  1512. the time being, and to stop until resumeProducing() is called.
  1513. """
  1514. pass
  1515. def resumeProducing(self):
  1516. """
  1517. Resume producing data.
  1518. This tells a producer to re-add itself to the main loop and produce
  1519. more data for its consumer.
  1520. """
  1521. pass
  1522. def registerProducer(self, producer, streaming):
  1523. """
  1524. Register to receive data from a producer.
  1525. @param producer: The producer to register.
  1526. @param streaming: Whether this is a streaming producer or not.
  1527. """
  1528. pass
  1529. def unregisterProducer(self):
  1530. """
  1531. Stop consuming data from a producer, without disconnecting.
  1532. """
  1533. pass
  1534. @implementer(interfaces.ITransport,
  1535. interfaces.IPushProducer,
  1536. interfaces.IConsumer)
  1537. class HTTPChannel(basic.LineReceiver, policies.TimeoutMixin):
  1538. """
  1539. A receiver for HTTP requests.
  1540. The L{HTTPChannel} provides L{interfaces.ITransport} and
  1541. L{interfaces.IConsumer} to the L{Request} objects it creates. It also
  1542. implements L{interfaces.IPushProducer} to C{self.transport}, allowing the
  1543. transport to pause it.
  1544. @ivar MAX_LENGTH: Maximum length for initial request line and each line
  1545. from the header.
  1546. @ivar _transferDecoder: L{None} or a decoder instance if the request body
  1547. uses the I{chunked} Transfer-Encoding.
  1548. @type _transferDecoder: L{_ChunkedTransferDecoder}
  1549. @ivar maxHeaders: Maximum number of headers allowed per request.
  1550. @type maxHeaders: C{int}
  1551. @ivar totalHeadersSize: Maximum bytes for request line plus all headers
  1552. from the request.
  1553. @type totalHeadersSize: C{int}
  1554. @ivar _receivedHeaderSize: Bytes received so far for the header.
  1555. @type _receivedHeaderSize: C{int}
  1556. @ivar _handlingRequest: Whether a request is currently being processed.
  1557. @type _handlingRequest: L{bool}
  1558. @ivar _dataBuffer: Any data that has been received from the connection
  1559. while processing an outstanding request.
  1560. @type _dataBuffer: L{list} of L{bytes}
  1561. @ivar _networkProducer: Either the transport, if it provides
  1562. L{interfaces.IPushProducer}, or a null implementation of
  1563. L{interfaces.IPushProducer}. Used to attempt to prevent the transport
  1564. from producing excess data when we're responding to a request.
  1565. @type _networkProducer: L{interfaces.IPushProducer}
  1566. @ivar _requestProducer: If the L{Request} object or anything it calls
  1567. registers itself as an L{interfaces.IProducer}, it will be stored here.
  1568. This is used to create a producing pipeline: pause/resume producing
  1569. methods will be propagated from the C{transport}, through the
  1570. L{HTTPChannel} instance, to the c{_requestProducer}.
  1571. The reason we proxy through the producing methods rather than the old
  1572. behaviour (where we literally just set the L{Request} object as the
  1573. producer on the transport) is because we want to be able to exert
  1574. backpressure on the client to prevent it from sending in arbitrarily
  1575. many requests without ever reading responses. Essentially, if the
  1576. client never reads our responses we will eventually stop reading its
  1577. requests.
  1578. @type _requestProducer: L{interfaces.IPushProducer}
  1579. @ivar _requestProducerStreaming: A boolean that tracks whether the producer
  1580. on the L{Request} side of this channel has registered itself as a
  1581. L{interfaces.IPushProducer} or an L{interfaces.IPullProducer}.
  1582. @type _requestProducerStreaming: L{bool} or L{None}
  1583. @ivar _waitingForTransport: A boolean that tracks whether the transport has
  1584. asked us to stop producing. This is used to keep track of what we're
  1585. waiting for: if the transport has asked us to stop producing then we
  1586. don't want to unpause the transport until it asks us to produce again.
  1587. @type _waitingForTransport: L{bool}
  1588. @ivar abortTimeout: The number of seconds to wait after we attempt to shut
  1589. the transport down cleanly to give up and forcibly terminate it. This
  1590. is only used when we time a connection out, to prevent errors causing
  1591. the FD to get leaked. If this is L{None}, we will wait forever.
  1592. @type abortTimeout: L{int}
  1593. @ivar _abortingCall: The L{twisted.internet.base.DelayedCall} that will be
  1594. used to forcibly close the transport if it doesn't close cleanly.
  1595. @type _abortingCall: L{twisted.internet.base.DelayedCall}
  1596. @ivar _optimisticEagerReadSize: When a resource takes a long time to answer
  1597. a request (via L{twisted.web.server.NOT_DONE_YET}, hopefully one day by
  1598. a L{Deferred}), we would like to be able to let that resource know
  1599. about the underlying transport disappearing as promptly as possible,
  1600. via L{Request.notifyFinish}, and therefore via
  1601. C{self.requests[...].connectionLost()} on this L{HTTPChannel}.
  1602. However, in order to simplify application logic, we implement
  1603. head-of-line blocking, and do not relay pipelined requests to the
  1604. application until the previous request has been answered. This means
  1605. that said application cannot dispose of any entity-body that comes in
  1606. from those subsequent requests, which may be arbitrarily large, and it
  1607. may need to be buffered in memory.
  1608. To implement this tradeoff between prompt notification when possible
  1609. (in the most frequent case of non-pipelined requests) and correct
  1610. behavior when not (say, if a client sends a very long-running GET
  1611. request followed by a PUT request with a very large body) we will
  1612. continue reading pipelined requests into C{self._dataBuffer} up to a
  1613. given limit.
  1614. C{_optimisticEagerReadSize} is the number of bytes we will accept from
  1615. the client and buffer before pausing the transport.
  1616. This behavior has been in place since Twisted 17.9.0 .
  1617. @type _optimisticEagerReadSize: L{int}
  1618. """
  1619. maxHeaders = 500
  1620. totalHeadersSize = 16384
  1621. abortTimeout = 15
  1622. length = 0
  1623. persistent = 1
  1624. __header = b''
  1625. __first_line = 1
  1626. __content = None
  1627. # set in instances or subclasses
  1628. requestFactory = Request
  1629. _savedTimeOut = None
  1630. _receivedHeaderCount = 0
  1631. _receivedHeaderSize = 0
  1632. _requestProducer = None
  1633. _requestProducerStreaming = None
  1634. _waitingForTransport = False
  1635. _abortingCall = None
  1636. _optimisticEagerReadSize = 0x4000
  1637. _log = Logger()
  1638. def __init__(self):
  1639. # the request queue
  1640. self.requests = []
  1641. self._handlingRequest = False
  1642. self._dataBuffer = []
  1643. self._transferDecoder = None
  1644. def connectionMade(self):
  1645. self.setTimeout(self.timeOut)
  1646. self._networkProducer = interfaces.IPushProducer(
  1647. self.transport, _NoPushProducer()
  1648. )
  1649. self._networkProducer.registerProducer(self, True)
  1650. def lineReceived(self, line):
  1651. """
  1652. Called for each line from request until the end of headers when
  1653. it enters binary mode.
  1654. """
  1655. self.resetTimeout()
  1656. self._receivedHeaderSize += len(line)
  1657. if (self._receivedHeaderSize > self.totalHeadersSize):
  1658. self._respondToBadRequestAndDisconnect()
  1659. return
  1660. if self.__first_line:
  1661. # if this connection is not persistent, drop any data which
  1662. # the client (illegally) sent after the last request.
  1663. if not self.persistent:
  1664. self.dataReceived = self.lineReceived = lambda *args: None
  1665. return
  1666. # IE sends an extraneous empty line (\r\n) after a POST request;
  1667. # eat up such a line, but only ONCE
  1668. if not line and self.__first_line == 1:
  1669. self.__first_line = 2
  1670. return
  1671. # create a new Request object
  1672. if INonQueuedRequestFactory.providedBy(self.requestFactory):
  1673. request = self.requestFactory(self)
  1674. else:
  1675. request = self.requestFactory(self, len(self.requests))
  1676. self.requests.append(request)
  1677. self.__first_line = 0
  1678. parts = line.split()
  1679. if len(parts) != 3:
  1680. self._respondToBadRequestAndDisconnect()
  1681. return
  1682. command, request, version = parts
  1683. try:
  1684. command.decode("ascii")
  1685. except UnicodeDecodeError:
  1686. self._respondToBadRequestAndDisconnect()
  1687. return
  1688. self._command = command
  1689. self._path = request
  1690. self._version = version
  1691. elif line == b'':
  1692. # End of headers.
  1693. if self.__header:
  1694. ok = self.headerReceived(self.__header)
  1695. # If the last header we got is invalid, we MUST NOT proceed
  1696. # with processing. We'll have sent a 400 anyway, so just stop.
  1697. if not ok:
  1698. return
  1699. self.__header = b''
  1700. self.allHeadersReceived()
  1701. if self.length == 0:
  1702. self.allContentReceived()
  1703. else:
  1704. self.setRawMode()
  1705. elif line[0] in b' \t':
  1706. # Continuation of a multi line header.
  1707. self.__header = self.__header + b'\n' + line
  1708. # Regular header line.
  1709. # Processing of header line is delayed to allow accumulating multi
  1710. # line headers.
  1711. else:
  1712. if self.__header:
  1713. self.headerReceived(self.__header)
  1714. self.__header = line
  1715. def _finishRequestBody(self, data):
  1716. self.allContentReceived()
  1717. self._dataBuffer.append(data)
  1718. def _maybeChooseTransferDecoder(self, header, data):
  1719. """
  1720. If the provided header is C{content-length} or
  1721. C{transfer-encoding}, choose the appropriate decoder if any.
  1722. Returns L{True} if the request can proceed and L{False} if not.
  1723. """
  1724. def fail():
  1725. self._respondToBadRequestAndDisconnect()
  1726. self.length = None
  1727. return False
  1728. # Can this header determine the length?
  1729. if header == b'content-length':
  1730. try:
  1731. length = int(data)
  1732. except ValueError:
  1733. return fail()
  1734. newTransferDecoder = _IdentityTransferDecoder(
  1735. length, self.requests[-1].handleContentChunk,
  1736. self._finishRequestBody)
  1737. elif header == b'transfer-encoding':
  1738. # XXX Rather poorly tested code block, apparently only exercised by
  1739. # test_chunkedEncoding
  1740. if data.lower() == b'chunked':
  1741. length = None
  1742. newTransferDecoder = _ChunkedTransferDecoder(
  1743. self.requests[-1].handleContentChunk,
  1744. self._finishRequestBody)
  1745. elif data.lower() == b'identity':
  1746. return True
  1747. else:
  1748. return fail()
  1749. else:
  1750. # It's not a length related header, so exit
  1751. return True
  1752. if self._transferDecoder is not None:
  1753. return fail()
  1754. else:
  1755. self.length = length
  1756. self._transferDecoder = newTransferDecoder
  1757. return True
  1758. def headerReceived(self, line):
  1759. """
  1760. Do pre-processing (for content-length) and store this header away.
  1761. Enforce the per-request header limit.
  1762. @type line: C{bytes}
  1763. @param line: A line from the header section of a request, excluding the
  1764. line delimiter.
  1765. @return: A flag indicating whether the header was valid.
  1766. @rtype: L{bool}
  1767. """
  1768. try:
  1769. header, data = line.split(b':', 1)
  1770. except ValueError:
  1771. self._respondToBadRequestAndDisconnect()
  1772. return False
  1773. if not header or header[-1:].isspace():
  1774. self._respondToBadRequestAndDisconnect()
  1775. return False
  1776. header = header.lower()
  1777. data = data.strip()
  1778. if not self._maybeChooseTransferDecoder(header, data):
  1779. return False
  1780. reqHeaders = self.requests[-1].requestHeaders
  1781. values = reqHeaders.getRawHeaders(header)
  1782. if values is not None:
  1783. values.append(data)
  1784. else:
  1785. reqHeaders.setRawHeaders(header, [data])
  1786. self._receivedHeaderCount += 1
  1787. if self._receivedHeaderCount > self.maxHeaders:
  1788. self._respondToBadRequestAndDisconnect()
  1789. return False
  1790. return True
  1791. def allContentReceived(self):
  1792. command = self._command
  1793. path = self._path
  1794. version = self._version
  1795. # reset ALL state variables, so we don't interfere with next request
  1796. self.length = 0
  1797. self._receivedHeaderCount = 0
  1798. self._receivedHeaderSize = 0
  1799. self.__first_line = 1
  1800. self._transferDecoder = None
  1801. del self._command, self._path, self._version
  1802. # Disable the idle timeout, in case this request takes a long
  1803. # time to finish generating output.
  1804. if self.timeOut:
  1805. self._savedTimeOut = self.setTimeout(None)
  1806. self._handlingRequest = True
  1807. req = self.requests[-1]
  1808. req.requestReceived(command, path, version)
  1809. def dataReceived(self, data):
  1810. """
  1811. Data was received from the network. Process it.
  1812. """
  1813. # If we're currently handling a request, buffer this data.
  1814. if self._handlingRequest:
  1815. self._dataBuffer.append(data)
  1816. if (
  1817. (sum(map(len, self._dataBuffer)) >
  1818. self._optimisticEagerReadSize)
  1819. and not self._waitingForTransport
  1820. ):
  1821. # If we received more data than a small limit while processing
  1822. # the head-of-line request, apply TCP backpressure to our peer
  1823. # to get them to stop sending more request data until we're
  1824. # ready. See docstring for _optimisticEagerReadSize above.
  1825. self._networkProducer.pauseProducing()
  1826. return
  1827. return basic.LineReceiver.dataReceived(self, data)
  1828. def rawDataReceived(self, data):
  1829. self.resetTimeout()
  1830. try:
  1831. self._transferDecoder.dataReceived(data)
  1832. except _MalformedChunkedDataError:
  1833. self._respondToBadRequestAndDisconnect()
  1834. def allHeadersReceived(self):
  1835. req = self.requests[-1]
  1836. req.parseCookies()
  1837. self.persistent = self.checkPersistence(req, self._version)
  1838. req.gotLength(self.length)
  1839. # Handle 'Expect: 100-continue' with automated 100 response code,
  1840. # a simplistic implementation of RFC 2686 8.2.3:
  1841. expectContinue = req.requestHeaders.getRawHeaders(b'expect')
  1842. if (expectContinue and expectContinue[0].lower() == b'100-continue' and
  1843. self._version == b'HTTP/1.1'):
  1844. self._send100Continue()
  1845. def checkPersistence(self, request, version):
  1846. """
  1847. Check if the channel should close or not.
  1848. @param request: The request most recently received over this channel
  1849. against which checks will be made to determine if this connection
  1850. can remain open after a matching response is returned.
  1851. @type version: C{bytes}
  1852. @param version: The version of the request.
  1853. @rtype: C{bool}
  1854. @return: A flag which, if C{True}, indicates that this connection may
  1855. remain open to receive another request; if C{False}, the connection
  1856. must be closed in order to indicate the completion of the response
  1857. to C{request}.
  1858. """
  1859. connection = request.requestHeaders.getRawHeaders(b'connection')
  1860. if connection:
  1861. tokens = [t.lower() for t in connection[0].split(b' ')]
  1862. else:
  1863. tokens = []
  1864. # Once any HTTP 0.9 or HTTP 1.0 request is received, the connection is
  1865. # no longer allowed to be persistent. At this point in processing the
  1866. # request, we don't yet know if it will be possible to set a
  1867. # Content-Length in the response. If it is not, then the connection
  1868. # will have to be closed to end an HTTP 0.9 or HTTP 1.0 response.
  1869. # If the checkPersistence call happened later, after the Content-Length
  1870. # has been determined (or determined not to be set), it would probably
  1871. # be possible to have persistent connections with HTTP 0.9 and HTTP 1.0.
  1872. # This may not be worth the effort, though. Just use HTTP 1.1, okay?
  1873. if version == b"HTTP/1.1":
  1874. if b'close' in tokens:
  1875. request.responseHeaders.setRawHeaders(b'connection', [b'close'])
  1876. return False
  1877. else:
  1878. return True
  1879. else:
  1880. return False
  1881. def requestDone(self, request):
  1882. """
  1883. Called by first request in queue when it is done.
  1884. """
  1885. if request != self.requests[0]: raise TypeError
  1886. del self.requests[0]
  1887. # We should only resume the producer if we're not waiting for the
  1888. # transport.
  1889. if not self._waitingForTransport:
  1890. self._networkProducer.resumeProducing()
  1891. if self.persistent:
  1892. self._handlingRequest = False
  1893. if self._savedTimeOut:
  1894. self.setTimeout(self._savedTimeOut)
  1895. # Receive our buffered data, if any.
  1896. data = b''.join(self._dataBuffer)
  1897. self._dataBuffer = []
  1898. self.setLineMode(data)
  1899. else:
  1900. self.loseConnection()
  1901. def timeoutConnection(self):
  1902. self._log.info(
  1903. "Timing out client: {peer}",
  1904. peer=str(self.transport.getPeer())
  1905. )
  1906. if self.abortTimeout is not None:
  1907. # We use self.callLater because that's what TimeoutMixin does.
  1908. self._abortingCall = self.callLater(
  1909. self.abortTimeout, self.forceAbortClient
  1910. )
  1911. self.loseConnection()
  1912. def forceAbortClient(self):
  1913. """
  1914. Called if C{abortTimeout} seconds have passed since the timeout fired,
  1915. and the connection still hasn't gone away. This can really only happen
  1916. on extremely bad connections or when clients are maliciously attempting
  1917. to keep connections open.
  1918. """
  1919. self._log.info(
  1920. "Forcibly timing out client: {peer}",
  1921. peer=str(self.transport.getPeer())
  1922. )
  1923. # We want to lose track of the _abortingCall so that no-one tries to
  1924. # cancel it.
  1925. self._abortingCall = None
  1926. self.transport.abortConnection()
  1927. def connectionLost(self, reason):
  1928. self.setTimeout(None)
  1929. for request in self.requests:
  1930. request.connectionLost(reason)
  1931. # If we were going to force-close the transport, we don't have to now.
  1932. if self._abortingCall is not None:
  1933. self._abortingCall.cancel()
  1934. self._abortingCall = None
  1935. def isSecure(self):
  1936. """
  1937. Return L{True} if this channel is using a secure transport.
  1938. Normally this method returns L{True} if this instance is using a
  1939. transport that implements L{interfaces.ISSLTransport}.
  1940. @returns: L{True} if this request is secure
  1941. @rtype: C{bool}
  1942. """
  1943. if interfaces.ISSLTransport(self.transport, None) is not None:
  1944. return True
  1945. return False
  1946. def writeHeaders(self, version, code, reason, headers):
  1947. """
  1948. Called by L{Request} objects to write a complete set of HTTP headers to
  1949. a transport.
  1950. @param version: The HTTP version in use.
  1951. @type version: L{bytes}
  1952. @param code: The HTTP status code to write.
  1953. @type code: L{bytes}
  1954. @param reason: The HTTP reason phrase to write.
  1955. @type reason: L{bytes}
  1956. @param headers: The headers to write to the transport.
  1957. @type headers: L{twisted.web.http_headers.Headers}
  1958. """
  1959. sanitizedHeaders = Headers()
  1960. for name, value in headers:
  1961. sanitizedHeaders.addRawHeader(name, value)
  1962. responseLine = version + b" " + code + b" " + reason + b"\r\n"
  1963. headerSequence = [responseLine]
  1964. headerSequence.extend(
  1965. name + b': ' + value + b"\r\n"
  1966. for name, values in sanitizedHeaders.getAllRawHeaders()
  1967. for value in values
  1968. )
  1969. headerSequence.append(b"\r\n")
  1970. self.transport.writeSequence(headerSequence)
  1971. def write(self, data):
  1972. """
  1973. Called by L{Request} objects to write response data.
  1974. @param data: The data chunk to write to the stream.
  1975. @type data: L{bytes}
  1976. @return: L{None}
  1977. """
  1978. self.transport.write(data)
  1979. def writeSequence(self, iovec):
  1980. """
  1981. Write a list of strings to the HTTP response.
  1982. @param iovec: A list of byte strings to write to the stream.
  1983. @type data: L{list} of L{bytes}
  1984. @return: L{None}
  1985. """
  1986. self.transport.writeSequence(iovec)
  1987. def getPeer(self):
  1988. """
  1989. Get the remote address of this connection.
  1990. @return: An L{IAddress} provider.
  1991. """
  1992. return self.transport.getPeer()
  1993. def getHost(self):
  1994. """
  1995. Get the local address of this connection.
  1996. @return: An L{IAddress} provider.
  1997. """
  1998. return self.transport.getHost()
  1999. def loseConnection(self):
  2000. """
  2001. Closes the connection. Will write any data that is pending to be sent
  2002. on the network, but if this response has not yet been written to the
  2003. network will not write anything.
  2004. @return: L{None}
  2005. """
  2006. self._networkProducer.unregisterProducer()
  2007. return self.transport.loseConnection()
  2008. def registerProducer(self, producer, streaming):
  2009. """
  2010. Register to receive data from a producer.
  2011. This sets self to be a consumer for a producer. When this object runs
  2012. out of data (as when a send(2) call on a socket succeeds in moving the
  2013. last data from a userspace buffer into a kernelspace buffer), it will
  2014. ask the producer to resumeProducing().
  2015. For L{IPullProducer} providers, C{resumeProducing} will be called once
  2016. each time data is required.
  2017. For L{IPushProducer} providers, C{pauseProducing} will be called
  2018. whenever the write buffer fills up and C{resumeProducing} will only be
  2019. called when it empties.
  2020. @type producer: L{IProducer} provider
  2021. @param producer: The L{IProducer} that will be producing data.
  2022. @type streaming: L{bool}
  2023. @param streaming: C{True} if C{producer} provides L{IPushProducer},
  2024. C{False} if C{producer} provides L{IPullProducer}.
  2025. @raise RuntimeError: If a producer is already registered.
  2026. @return: L{None}
  2027. """
  2028. if self._requestProducer is not None:
  2029. raise RuntimeError(
  2030. "Cannot register producer %s, because producer %s was never "
  2031. "unregistered." % (producer, self._requestProducer))
  2032. if not streaming:
  2033. producer = _PullToPush(producer, self)
  2034. self._requestProducer = producer
  2035. self._requestProducerStreaming = streaming
  2036. if not streaming:
  2037. producer.startStreaming()
  2038. def unregisterProducer(self):
  2039. """
  2040. Stop consuming data from a producer, without disconnecting.
  2041. @return: L{None}
  2042. """
  2043. if self._requestProducer is None:
  2044. return
  2045. if not self._requestProducerStreaming:
  2046. self._requestProducer.stopStreaming()
  2047. self._requestProducer = None
  2048. self._requestProducerStreaming = None
  2049. def stopProducing(self):
  2050. """
  2051. Stop producing data.
  2052. The HTTPChannel doesn't *actually* implement this, beacuse the
  2053. assumption is that it will only be called just before C{loseConnection}
  2054. is called. There's nothing sensible we can do other than call
  2055. C{loseConnection} anyway.
  2056. """
  2057. if self._requestProducer is not None:
  2058. self._requestProducer.stopProducing()
  2059. def pauseProducing(self):
  2060. """
  2061. Pause producing data.
  2062. This will be called by the transport when the send buffers have been
  2063. filled up. We want to simultaneously pause the producing L{Request}
  2064. object and also pause our transport.
  2065. The logic behind pausing the transport is specifically to avoid issues
  2066. like https://twistedmatrix.com/trac/ticket/8868. In this case, our
  2067. inability to send does not prevent us handling more requests, which
  2068. means we increasingly queue up more responses in our send buffer
  2069. without end. The easiest way to handle this is to ensure that if we are
  2070. unable to send our responses, we will not read further data from the
  2071. connection until the client pulls some data out. This is a bit of a
  2072. blunt instrument, but it's ok.
  2073. Note that this potentially interacts with timeout handling in a
  2074. positive way. Once the transport is paused the client may run into a
  2075. timeout which will cause us to tear the connection down. That's a good
  2076. thing!
  2077. """
  2078. self._waitingForTransport = True
  2079. # The first step is to tell any producer we might currently have
  2080. # registered to stop producing. If we can slow our applications down
  2081. # we should.
  2082. if self._requestProducer is not None:
  2083. self._requestProducer.pauseProducing()
  2084. # The next step here is to pause our own transport, as discussed in the
  2085. # docstring.
  2086. if not self._handlingRequest:
  2087. self._networkProducer.pauseProducing()
  2088. def resumeProducing(self):
  2089. """
  2090. Resume producing data.
  2091. This will be called by the transport when the send buffer has dropped
  2092. enough to actually send more data. When this happens we can unpause any
  2093. outstanding L{Request} producers we have, and also unpause our
  2094. transport.
  2095. """
  2096. self._waitingForTransport = False
  2097. if self._requestProducer is not None:
  2098. self._requestProducer.resumeProducing()
  2099. # We only want to resume the network producer if we're not currently
  2100. # waiting for a response to show up.
  2101. if not self._handlingRequest:
  2102. self._networkProducer.resumeProducing()
  2103. def _send100Continue(self):
  2104. """
  2105. Sends a 100 Continue response, used to signal to clients that further
  2106. processing will be performed.
  2107. """
  2108. self.transport.write(b"HTTP/1.1 100 Continue\r\n\r\n")
  2109. def _respondToBadRequestAndDisconnect(self):
  2110. """
  2111. This is a quick and dirty way of responding to bad requests.
  2112. As described by HTTP standard we should be patient and accept the
  2113. whole request from the client before sending a polite bad request
  2114. response, even in the case when clients send tons of data.
  2115. @param transport: Transport handling connection to the client.
  2116. @type transport: L{interfaces.ITransport}
  2117. """
  2118. self.transport.write(b"HTTP/1.1 400 Bad Request\r\n\r\n")
  2119. self.loseConnection()
  2120. def _escape(s):
  2121. """
  2122. Return a string like python repr, but always escaped as if surrounding
  2123. quotes were double quotes.
  2124. @param s: The string to escape.
  2125. @type s: L{bytes} or L{unicode}
  2126. @return: An escaped string.
  2127. @rtype: L{unicode}
  2128. """
  2129. if not isinstance(s, bytes):
  2130. s = s.encode("ascii")
  2131. r = repr(s)
  2132. if not isinstance(r, unicode):
  2133. r = r.decode("ascii")
  2134. if r.startswith(u"b"):
  2135. r = r[1:]
  2136. if r.startswith(u"'"):
  2137. return r[1:-1].replace(u'"', u'\\"').replace(u"\\'", u"'")
  2138. return r[1:-1]
  2139. @provider(IAccessLogFormatter)
  2140. def combinedLogFormatter(timestamp, request):
  2141. """
  2142. @return: A combined log formatted log line for the given request.
  2143. @see: L{IAccessLogFormatter}
  2144. """
  2145. clientAddr = request.getClientAddress()
  2146. if isinstance(clientAddr, (address.IPv4Address, address.IPv6Address,
  2147. _XForwardedForAddress)):
  2148. ip = clientAddr.host
  2149. else:
  2150. ip = b'-'
  2151. referrer = _escape(request.getHeader(b"referer") or b"-")
  2152. agent = _escape(request.getHeader(b"user-agent") or b"-")
  2153. line = (
  2154. u'"%(ip)s" - - %(timestamp)s "%(method)s %(uri)s %(protocol)s" '
  2155. u'%(code)d %(length)s "%(referrer)s" "%(agent)s"' % dict(
  2156. ip=_escape(ip),
  2157. timestamp=timestamp,
  2158. method=_escape(request.method),
  2159. uri=_escape(request.uri),
  2160. protocol=_escape(request.clientproto),
  2161. code=request.code,
  2162. length=request.sentLength or u"-",
  2163. referrer=referrer,
  2164. agent=agent,
  2165. ))
  2166. return line
  2167. @implementer(interfaces.IAddress)
  2168. class _XForwardedForAddress(object):
  2169. """
  2170. L{IAddress} which represents the client IP to log for a request, as gleaned
  2171. from an X-Forwarded-For header.
  2172. @ivar host: An IP address or C{b"-"}.
  2173. @type host: L{bytes}
  2174. @see: L{proxiedLogFormatter}
  2175. """
  2176. def __init__(self, host):
  2177. self.host = host
  2178. class _XForwardedForRequest(proxyForInterface(IRequest, "_request")):
  2179. """
  2180. Add a layer on top of another request that only uses the value of an
  2181. X-Forwarded-For header as the result of C{getClientAddress}.
  2182. """
  2183. def getClientAddress(self):
  2184. """
  2185. The client address (the first address) in the value of the
  2186. I{X-Forwarded-For header}. If the header is not present, the IP is
  2187. considered to be C{b"-"}.
  2188. @return: L{_XForwardedForAddress} which wraps the client address as
  2189. expected by L{combinedLogFormatter}.
  2190. """
  2191. host = self._request.requestHeaders.getRawHeaders(
  2192. b"x-forwarded-for", [b"-"])[0].split(b",")[0].strip()
  2193. return _XForwardedForAddress(host)
  2194. # These are missing from the interface. Forward them manually.
  2195. @property
  2196. def clientproto(self):
  2197. """
  2198. @return: The protocol version in the request.
  2199. @rtype: L{bytes}
  2200. """
  2201. return self._request.clientproto
  2202. @property
  2203. def code(self):
  2204. """
  2205. @return: The response code for the request.
  2206. @rtype: L{int}
  2207. """
  2208. return self._request.code
  2209. @property
  2210. def sentLength(self):
  2211. """
  2212. @return: The number of bytes sent in the response body.
  2213. @rtype: L{int}
  2214. """
  2215. return self._request.sentLength
  2216. @provider(IAccessLogFormatter)
  2217. def proxiedLogFormatter(timestamp, request):
  2218. """
  2219. @return: A combined log formatted log line for the given request but use
  2220. the value of the I{X-Forwarded-For} header as the value for the client
  2221. IP address.
  2222. @see: L{IAccessLogFormatter}
  2223. """
  2224. return combinedLogFormatter(timestamp, _XForwardedForRequest(request))
  2225. class _GenericHTTPChannelProtocol(proxyForInterface(IProtocol, "_channel")):
  2226. """
  2227. A proxy object that wraps one of the HTTP protocol objects, and switches
  2228. between them depending on TLS negotiated protocol.
  2229. @ivar _negotiatedProtocol: The protocol negotiated with ALPN or NPN, if
  2230. any.
  2231. @type _negotiatedProtocol: Either a bytestring containing the ALPN token
  2232. for the negotiated protocol, or L{None} if no protocol has yet been
  2233. negotiated.
  2234. @ivar _channel: The object capable of behaving like a L{HTTPChannel} that
  2235. is backing this object. By default this is a L{HTTPChannel}, but if a
  2236. HTTP protocol upgrade takes place this may be a different channel
  2237. object. Must implement L{IProtocol}.
  2238. @type _channel: L{HTTPChannel}
  2239. @ivar _requestFactory: A callable to use to build L{IRequest} objects.
  2240. @type _requestFactory: L{IRequest}
  2241. @ivar _site: A reference to the creating L{twisted.web.server.Site} object.
  2242. @type _site: L{twisted.web.server.Site}
  2243. @ivar _factory: A reference to the creating L{HTTPFactory} object.
  2244. @type _factory: L{HTTPFactory}
  2245. @ivar _timeOut: A timeout value to pass to the backing channel.
  2246. @type _timeOut: L{int} or L{None}
  2247. @ivar _callLater: A value for the C{callLater} callback.
  2248. @type _callLater: L{callable}
  2249. """
  2250. _negotiatedProtocol = None
  2251. _requestFactory = Request
  2252. _factory = None
  2253. _site = None
  2254. _timeOut = None
  2255. _callLater = None
  2256. @property
  2257. def factory(self):
  2258. """
  2259. @see: L{_genericHTTPChannelProtocolFactory}
  2260. """
  2261. return self._channel.factory
  2262. @factory.setter
  2263. def factory(self, value):
  2264. self._factory = value
  2265. self._channel.factory = value
  2266. @property
  2267. def requestFactory(self):
  2268. """
  2269. A callable to use to build L{IRequest} objects.
  2270. Retries the object from the current backing channel.
  2271. """
  2272. return self._channel.requestFactory
  2273. @requestFactory.setter
  2274. def requestFactory(self, value):
  2275. """
  2276. A callable to use to build L{IRequest} objects.
  2277. Sets the object on the backing channel and also stores the value for
  2278. propagation to any new channel.
  2279. @param value: The new callable to use.
  2280. @type value: A L{callable} returning L{IRequest}
  2281. """
  2282. self._requestFactory = value
  2283. self._channel.requestFactory = value
  2284. @property
  2285. def site(self):
  2286. """
  2287. A reference to the creating L{twisted.web.server.Site} object.
  2288. Returns the site object from the backing channel.
  2289. """
  2290. return self._channel.site
  2291. @site.setter
  2292. def site(self, value):
  2293. """
  2294. A reference to the creating L{twisted.web.server.Site} object.
  2295. Sets the object on the backing channel and also stores the value for
  2296. propagation to any new channel.
  2297. @param value: The L{twisted.web.server.Site} object to set.
  2298. @type value: L{twisted.web.server.Site}
  2299. """
  2300. self._site = value
  2301. self._channel.site = value
  2302. @property
  2303. def timeOut(self):
  2304. """
  2305. The idle timeout for the backing channel.
  2306. """
  2307. return self._channel.timeOut
  2308. @timeOut.setter
  2309. def timeOut(self, value):
  2310. """
  2311. The idle timeout for the backing channel.
  2312. Sets the idle timeout on both the backing channel and stores it for
  2313. propagation to any new backing channel.
  2314. @param value: The timeout to set.
  2315. @type value: L{int} or L{float}
  2316. """
  2317. self._timeOut = value
  2318. self._channel.timeOut = value
  2319. @property
  2320. def callLater(self):
  2321. """
  2322. A value for the C{callLater} callback. This callback is used by the
  2323. L{twisted.protocols.policies.TimeoutMixin} to handle timeouts.
  2324. """
  2325. return self._channel.callLater
  2326. @callLater.setter
  2327. def callLater(self, value):
  2328. """
  2329. Sets the value for the C{callLater} callback. This callback is used by
  2330. the L{twisted.protocols.policies.TimeoutMixin} to handle timeouts.
  2331. @param value: The new callback to use.
  2332. @type value: L{callable}
  2333. """
  2334. self._callLater = value
  2335. self._channel.callLater = value
  2336. def dataReceived(self, data):
  2337. """
  2338. An override of L{IProtocol.dataReceived} that checks what protocol we're
  2339. using.
  2340. """
  2341. if self._negotiatedProtocol is None:
  2342. try:
  2343. negotiatedProtocol = self._channel.transport.negotiatedProtocol
  2344. except AttributeError:
  2345. # Plaintext HTTP, always HTTP/1.1
  2346. negotiatedProtocol = b'http/1.1'
  2347. if negotiatedProtocol is None:
  2348. negotiatedProtocol = b'http/1.1'
  2349. if negotiatedProtocol == b'h2':
  2350. if not H2_ENABLED:
  2351. raise ValueError("Negotiated HTTP/2 without support.")
  2352. # We need to make sure that the HTTPChannel is unregistered
  2353. # from the transport so that the H2Connection can register
  2354. # itself if possible.
  2355. networkProducer = self._channel._networkProducer
  2356. networkProducer.unregisterProducer()
  2357. # Cancel the old channel's timeout.
  2358. self._channel.setTimeout(None)
  2359. # Cancel the old channel's timeout.
  2360. self._channel.setTimeout(None)
  2361. transport = self._channel.transport
  2362. self._channel = H2Connection()
  2363. self._channel.requestFactory = self._requestFactory
  2364. self._channel.site = self._site
  2365. self._channel.factory = self._factory
  2366. self._channel.timeOut = self._timeOut
  2367. self._channel.callLater = self._callLater
  2368. self._channel.makeConnection(transport)
  2369. # Register the H2Connection as the transport's
  2370. # producer, so that the transport can apply back
  2371. # pressure.
  2372. networkProducer.registerProducer(self._channel, True)
  2373. else:
  2374. # Only HTTP/2 and HTTP/1.1 are supported right now.
  2375. assert negotiatedProtocol == b'http/1.1', \
  2376. "Unsupported protocol negotiated"
  2377. self._negotiatedProtocol = negotiatedProtocol
  2378. return self._channel.dataReceived(data)
  2379. def _genericHTTPChannelProtocolFactory(self):
  2380. """
  2381. Returns an appropriately initialized _GenericHTTPChannelProtocol.
  2382. """
  2383. return _GenericHTTPChannelProtocol(HTTPChannel())
  2384. class HTTPFactory(protocol.ServerFactory):
  2385. """
  2386. Factory for HTTP server.
  2387. @ivar _logDateTime: A cached datetime string for log messages, updated by
  2388. C{_logDateTimeCall}.
  2389. @type _logDateTime: C{str}
  2390. @ivar _logDateTimeCall: A delayed call for the next update to the cached
  2391. log datetime string.
  2392. @type _logDateTimeCall: L{IDelayedCall} provided
  2393. @ivar _logFormatter: See the C{logFormatter} parameter to L{__init__}
  2394. @ivar _nativeize: A flag that indicates whether the log file being written
  2395. to wants native strings (C{True}) or bytes (C{False}). This is only to
  2396. support writing to L{twisted.python.log} which, unfortunately, works
  2397. with native strings.
  2398. @ivar _reactor: An L{IReactorTime} provider used to compute logging
  2399. timestamps.
  2400. """
  2401. protocol = _genericHTTPChannelProtocolFactory
  2402. logPath = None
  2403. timeOut = _REQUEST_TIMEOUT
  2404. def __init__(self, logPath=None, timeout=_REQUEST_TIMEOUT,
  2405. logFormatter=None, reactor=None):
  2406. """
  2407. @param logPath: File path to which access log messages will be written
  2408. or C{None} to disable logging.
  2409. @type logPath: L{str} or L{bytes}
  2410. @param timeout: The initial value of L{timeOut}, which defines the idle
  2411. connection timeout in seconds, or C{None} to disable the idle
  2412. timeout.
  2413. @type timeout: L{float}
  2414. @param logFormatter: An object to format requests into log lines for
  2415. the access log. L{combinedLogFormatter} when C{None} is passed.
  2416. @type logFormatter: L{IAccessLogFormatter} provider
  2417. @param reactor: A L{IReactorTime} provider used to manage connection
  2418. timeouts and compute logging timestamps.
  2419. """
  2420. if not reactor:
  2421. from twisted.internet import reactor
  2422. self._reactor = reactor
  2423. if logPath is not None:
  2424. logPath = os.path.abspath(logPath)
  2425. self.logPath = logPath
  2426. self.timeOut = timeout
  2427. if logFormatter is None:
  2428. logFormatter = combinedLogFormatter
  2429. self._logFormatter = logFormatter
  2430. # For storing the cached log datetime and the callback to update it
  2431. self._logDateTime = None
  2432. self._logDateTimeCall = None
  2433. def _updateLogDateTime(self):
  2434. """
  2435. Update log datetime periodically, so we aren't always recalculating it.
  2436. """
  2437. self._logDateTime = datetimeToLogString(self._reactor.seconds())
  2438. self._logDateTimeCall = self._reactor.callLater(1, self._updateLogDateTime)
  2439. def buildProtocol(self, addr):
  2440. p = protocol.ServerFactory.buildProtocol(self, addr)
  2441. # This is a bit of a hack to ensure that the HTTPChannel timeouts
  2442. # occur on the same reactor as the one we're using here. This could
  2443. # ideally be resolved by passing the reactor more generally to the
  2444. # HTTPChannel, but that won't work for the TimeoutMixin until we fix
  2445. # https://twistedmatrix.com/trac/ticket/8488
  2446. p.callLater = self._reactor.callLater
  2447. # timeOut needs to be on the Protocol instance cause
  2448. # TimeoutMixin expects it there
  2449. p.timeOut = self.timeOut
  2450. return p
  2451. def startFactory(self):
  2452. """
  2453. Set up request logging if necessary.
  2454. """
  2455. if self._logDateTimeCall is None:
  2456. self._updateLogDateTime()
  2457. if self.logPath:
  2458. self.logFile = self._openLogFile(self.logPath)
  2459. else:
  2460. self.logFile = log.logfile
  2461. def stopFactory(self):
  2462. if hasattr(self, "logFile"):
  2463. if self.logFile != log.logfile:
  2464. self.logFile.close()
  2465. del self.logFile
  2466. if self._logDateTimeCall is not None and self._logDateTimeCall.active():
  2467. self._logDateTimeCall.cancel()
  2468. self._logDateTimeCall = None
  2469. def _openLogFile(self, path):
  2470. """
  2471. Override in subclasses, e.g. to use L{twisted.python.logfile}.
  2472. """
  2473. f = open(path, "ab", 1)
  2474. return f
  2475. def log(self, request):
  2476. """
  2477. Write a line representing C{request} to the access log file.
  2478. @param request: The request object about which to log.
  2479. @type request: L{Request}
  2480. """
  2481. try:
  2482. logFile = self.logFile
  2483. except AttributeError:
  2484. pass
  2485. else:
  2486. line = self._logFormatter(self._logDateTime, request) + u"\n"
  2487. logFile.write(line.encode('utf8'))