http.py 92 KB

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