server.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  1. # -*- test-case-name: twisted.web.test.test_web -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. This is a web server which integrates with the twisted.internet infrastructure.
  6. @var NOT_DONE_YET: A token value which L{twisted.web.resource.IResource.render}
  7. implementations can return to indicate that the application will later call
  8. C{.write} and C{.finish} to complete the request, and that the HTTP
  9. connection should be left open.
  10. @type NOT_DONE_YET: Opaque; do not depend on any particular type for this
  11. value.
  12. """
  13. import copy
  14. import os
  15. import re
  16. import zlib
  17. from binascii import hexlify
  18. from html import escape
  19. from typing import List, Optional
  20. from urllib.parse import quote as _quote
  21. from zope.interface import implementer
  22. from twisted import copyright
  23. from twisted.internet import address, interfaces
  24. from twisted.internet.error import AlreadyCalled, AlreadyCancelled
  25. from twisted.logger import Logger
  26. from twisted.python import components, failure, reflect
  27. from twisted.python.compat import nativeString, networkString
  28. from twisted.spread.pb import Copyable, ViewPoint
  29. from twisted.web import http, iweb, resource, util
  30. from twisted.web.error import UnsupportedMethod
  31. from twisted.web.http import (
  32. NO_CONTENT,
  33. NOT_MODIFIED,
  34. HTTPFactory,
  35. Request as _HTTPRequest,
  36. datetimeToString,
  37. unquote,
  38. )
  39. NOT_DONE_YET = 1
  40. __all__ = [
  41. "supportedMethods",
  42. "Request",
  43. "Session",
  44. "Site",
  45. "version",
  46. "NOT_DONE_YET",
  47. "GzipEncoderFactory",
  48. ]
  49. # Support for other methods may be implemented on a per-resource basis.
  50. supportedMethods = (b"GET", b"HEAD", b"POST")
  51. def quote(string, *args, **kwargs):
  52. return _quote(string.decode("charmap"), *args, **kwargs).encode("charmap")
  53. def _addressToTuple(addr):
  54. if isinstance(addr, address.IPv4Address):
  55. return ("INET", addr.host, addr.port)
  56. elif isinstance(addr, address.UNIXAddress):
  57. return ("UNIX", addr.name)
  58. else:
  59. return tuple(addr)
  60. @implementer(iweb.IRequest)
  61. class Request(Copyable, http.Request, components.Componentized):
  62. """
  63. An HTTP request.
  64. @ivar defaultContentType: A L{bytes} giving the default I{Content-Type}
  65. value to send in responses if no other value is set. L{None} disables
  66. the default.
  67. @ivar _insecureSession: The L{Session} object representing state that will
  68. be transmitted over plain-text HTTP.
  69. @ivar _secureSession: The L{Session} object representing the state that
  70. will be transmitted only over HTTPS.
  71. """
  72. defaultContentType: Optional[bytes] = b"text/html"
  73. site = None
  74. appRootURL = None
  75. prepath: Optional[List[bytes]] = None
  76. postpath: Optional[List[bytes]] = None
  77. __pychecker__ = "unusednames=issuer"
  78. _inFakeHead = False
  79. _encoder = None
  80. _log = Logger()
  81. def __init__(self, *args, **kw):
  82. _HTTPRequest.__init__(self, *args, **kw)
  83. components.Componentized.__init__(self)
  84. def getStateToCopyFor(self, issuer):
  85. x = self.__dict__.copy()
  86. del x["transport"]
  87. # XXX refactor this attribute out; it's from protocol
  88. # del x['server']
  89. del x["channel"]
  90. del x["content"]
  91. del x["site"]
  92. self.content.seek(0, 0)
  93. x["content_data"] = self.content.read()
  94. x["remote"] = ViewPoint(issuer, self)
  95. # Address objects aren't jellyable
  96. x["host"] = _addressToTuple(x["host"])
  97. x["client"] = _addressToTuple(x["client"])
  98. # Header objects also aren't jellyable.
  99. x["requestHeaders"] = list(x["requestHeaders"].getAllRawHeaders())
  100. return x
  101. # HTML generation helpers
  102. def sibLink(self, name):
  103. """
  104. Return the text that links to a sibling of the requested resource.
  105. @param name: The sibling resource
  106. @type name: C{bytes}
  107. @return: A relative URL.
  108. @rtype: C{bytes}
  109. """
  110. if self.postpath:
  111. return (len(self.postpath) * b"../") + name
  112. else:
  113. return name
  114. def childLink(self, name):
  115. """
  116. Return the text that links to a child of the requested resource.
  117. @param name: The child resource
  118. @type name: C{bytes}
  119. @return: A relative URL.
  120. @rtype: C{bytes}
  121. """
  122. lpp = len(self.postpath)
  123. if lpp > 1:
  124. return ((lpp - 1) * b"../") + name
  125. elif lpp == 1:
  126. return name
  127. else: # lpp == 0
  128. if len(self.prepath) and self.prepath[-1]:
  129. return self.prepath[-1] + b"/" + name
  130. else:
  131. return name
  132. def gotLength(self, length):
  133. """
  134. Called when HTTP channel got length of content in this request.
  135. This method is not intended for users.
  136. @param length: The length of the request body, as indicated by the
  137. request headers. L{None} if the request headers do not indicate a
  138. length.
  139. """
  140. try:
  141. getContentFile = self.channel.site.getContentFile
  142. except AttributeError:
  143. _HTTPRequest.gotLength(self, length)
  144. else:
  145. self.content = getContentFile(length)
  146. def process(self):
  147. """
  148. Process a request.
  149. Find the addressed resource in this request's L{Site},
  150. and call L{self.render()<Request.render()>} with it.
  151. @see: L{Site.getResourceFor()}
  152. """
  153. # get site from channel
  154. self.site = self.channel.site
  155. # set various default headers
  156. self.setHeader(b"Server", version)
  157. self.setHeader(b"Date", datetimeToString())
  158. # Resource Identification
  159. self.prepath = []
  160. self.postpath = list(map(unquote, self.path[1:].split(b"/")))
  161. # Short-circuit for requests whose path is '*'.
  162. if self.path == b"*":
  163. self._handleStar()
  164. return
  165. try:
  166. resrc = self.site.getResourceFor(self)
  167. if resource._IEncodingResource.providedBy(resrc):
  168. encoder = resrc.getEncoder(self)
  169. if encoder is not None:
  170. self._encoder = encoder
  171. self.render(resrc)
  172. except BaseException:
  173. self.processingFailed(failure.Failure())
  174. def write(self, data):
  175. """
  176. Write data to the transport (if not responding to a HEAD request).
  177. @param data: A string to write to the response.
  178. @type data: L{bytes}
  179. """
  180. if not self.startedWriting:
  181. # Before doing the first write, check to see if a default
  182. # Content-Type header should be supplied. We omit it on
  183. # NOT_MODIFIED and NO_CONTENT responses. We also omit it if there
  184. # is a Content-Length header set to 0, as empty bodies don't need
  185. # a content-type.
  186. needsCT = self.code not in (NOT_MODIFIED, NO_CONTENT)
  187. contentType = self.responseHeaders.getRawHeaders(b"Content-Type")
  188. contentLength = self.responseHeaders.getRawHeaders(b"Content-Length")
  189. contentLengthZero = contentLength and (contentLength[0] == b"0")
  190. if (
  191. needsCT
  192. and contentType is None
  193. and self.defaultContentType is not None
  194. and not contentLengthZero
  195. ):
  196. self.responseHeaders.setRawHeaders(
  197. b"Content-Type", [self.defaultContentType]
  198. )
  199. # Only let the write happen if we're not generating a HEAD response by
  200. # faking out the request method. Note, if we are doing that,
  201. # startedWriting will never be true, and the above logic may run
  202. # multiple times. It will only actually change the responseHeaders
  203. # once though, so it's still okay.
  204. if not self._inFakeHead:
  205. if self._encoder:
  206. data = self._encoder.encode(data)
  207. _HTTPRequest.write(self, data)
  208. def finish(self):
  209. """
  210. Override L{twisted.web.http.Request.finish} for possible encoding.
  211. """
  212. if self._encoder:
  213. data = self._encoder.finish()
  214. if data:
  215. _HTTPRequest.write(self, data)
  216. return _HTTPRequest.finish(self)
  217. def render(self, resrc):
  218. """
  219. Ask a resource to render itself.
  220. If the resource does not support the requested method,
  221. generate a C{NOT IMPLEMENTED} or C{NOT ALLOWED} response.
  222. @param resrc: The resource to render.
  223. @type resrc: L{twisted.web.resource.IResource}
  224. @see: L{IResource.render()<twisted.web.resource.IResource.render()>}
  225. """
  226. try:
  227. body = resrc.render(self)
  228. except UnsupportedMethod as e:
  229. allowedMethods = e.allowedMethods
  230. if (self.method == b"HEAD") and (b"GET" in allowedMethods):
  231. # We must support HEAD (RFC 2616, 5.1.1). If the
  232. # resource doesn't, fake it by giving the resource
  233. # a 'GET' request and then return only the headers,
  234. # not the body.
  235. self._log.info(
  236. "Using GET to fake a HEAD request for {resrc}", resrc=resrc
  237. )
  238. self.method = b"GET"
  239. self._inFakeHead = True
  240. body = resrc.render(self)
  241. if body is NOT_DONE_YET:
  242. self._log.info(
  243. "Tried to fake a HEAD request for {resrc}, but "
  244. "it got away from me.",
  245. resrc=resrc,
  246. )
  247. # Oh well, I guess we won't include the content length.
  248. else:
  249. self.setHeader(b"Content-Length", b"%d" % (len(body),))
  250. self._inFakeHead = False
  251. self.method = b"HEAD"
  252. self.write(b"")
  253. self.finish()
  254. return
  255. if self.method in (supportedMethods):
  256. # We MUST include an Allow header
  257. # (RFC 2616, 10.4.6 and 14.7)
  258. self.setHeader(b"Allow", b", ".join(allowedMethods))
  259. s = (
  260. """Your browser approached me (at %(URI)s) with"""
  261. """ the method "%(method)s". I only allow"""
  262. """ the method%(plural)s %(allowed)s here."""
  263. % {
  264. "URI": escape(nativeString(self.uri)),
  265. "method": nativeString(self.method),
  266. "plural": ((len(allowedMethods) > 1) and "s") or "",
  267. "allowed": ", ".join([nativeString(x) for x in allowedMethods]),
  268. }
  269. )
  270. epage = resource._UnsafeErrorPage(
  271. http.NOT_ALLOWED, "Method Not Allowed", s
  272. )
  273. body = epage.render(self)
  274. else:
  275. epage = resource._UnsafeErrorPage(
  276. http.NOT_IMPLEMENTED,
  277. "Huh?",
  278. "I don't know how to treat a %s request."
  279. % (escape(self.method.decode("charmap")),),
  280. )
  281. body = epage.render(self)
  282. # end except UnsupportedMethod
  283. if body is NOT_DONE_YET:
  284. return
  285. if not isinstance(body, bytes):
  286. body = resource._UnsafeErrorPage(
  287. http.INTERNAL_SERVER_ERROR,
  288. "Request did not return bytes",
  289. "Request: "
  290. # GHSA-vg46-2rrj-3647 note: _PRE does HTML-escape the input.
  291. + util._PRE(reflect.safe_repr(self))
  292. + "<br />"
  293. + "Resource: "
  294. + util._PRE(reflect.safe_repr(resrc))
  295. + "<br />"
  296. + "Value: "
  297. + util._PRE(reflect.safe_repr(body)),
  298. ).render(self)
  299. if self.method == b"HEAD":
  300. if len(body) > 0:
  301. # This is a Bad Thing (RFC 2616, 9.4)
  302. self._log.info(
  303. "Warning: HEAD request {slf} for resource {resrc} is"
  304. " returning a message body. I think I'll eat it.",
  305. slf=self,
  306. resrc=resrc,
  307. )
  308. self.setHeader(b"Content-Length", b"%d" % (len(body),))
  309. self.write(b"")
  310. else:
  311. self.setHeader(b"Content-Length", b"%d" % (len(body),))
  312. self.write(body)
  313. self.finish()
  314. def processingFailed(self, reason):
  315. """
  316. Finish this request with an indication that processing failed and
  317. possibly display a traceback.
  318. @param reason: Reason this request has failed.
  319. @type reason: L{twisted.python.failure.Failure}
  320. @return: The reason passed to this method.
  321. @rtype: L{twisted.python.failure.Failure}
  322. """
  323. self._log.failure("", failure=reason)
  324. if self.site.displayTracebacks:
  325. body = (
  326. b"<html><head><title>web.Server Traceback"
  327. b" (most recent call last)</title></head>"
  328. b"<body><b>web.Server Traceback"
  329. b" (most recent call last):</b>\n\n"
  330. + util.formatFailure(reason)
  331. + b"\n\n</body></html>\n"
  332. )
  333. else:
  334. body = (
  335. b"<html><head><title>Processing Failed"
  336. b"</title></head><body>"
  337. b"<b>Processing Failed</b></body></html>"
  338. )
  339. self.setResponseCode(http.INTERNAL_SERVER_ERROR)
  340. self.setHeader(b"Content-Type", b"text/html")
  341. self.setHeader(b"Content-Length", b"%d" % (len(body),))
  342. self.write(body)
  343. self.finish()
  344. return reason
  345. def view_write(self, issuer, data):
  346. """Remote version of write; same interface."""
  347. self.write(data)
  348. def view_finish(self, issuer):
  349. """Remote version of finish; same interface."""
  350. self.finish()
  351. def view_addCookie(self, issuer, k, v, **kwargs):
  352. """Remote version of addCookie; same interface."""
  353. self.addCookie(k, v, **kwargs)
  354. def view_setHeader(self, issuer, k, v):
  355. """Remote version of setHeader; same interface."""
  356. self.setHeader(k, v)
  357. def view_setLastModified(self, issuer, when):
  358. """Remote version of setLastModified; same interface."""
  359. self.setLastModified(when)
  360. def view_setETag(self, issuer, tag):
  361. """Remote version of setETag; same interface."""
  362. self.setETag(tag)
  363. def view_setResponseCode(self, issuer, code, message=None):
  364. """
  365. Remote version of setResponseCode; same interface.
  366. """
  367. self.setResponseCode(code, message)
  368. def view_registerProducer(self, issuer, producer, streaming):
  369. """Remote version of registerProducer; same interface.
  370. (requires a remote producer.)
  371. """
  372. self.registerProducer(_RemoteProducerWrapper(producer), streaming)
  373. def view_unregisterProducer(self, issuer):
  374. self.unregisterProducer()
  375. ### these calls remain local
  376. _secureSession = None
  377. _insecureSession = None
  378. @property
  379. def session(self):
  380. """
  381. If a session has already been created or looked up with
  382. L{Request.getSession}, this will return that object. (This will always
  383. be the session that matches the security of the request; so if
  384. C{forceNotSecure} is used on a secure request, this will not return
  385. that session.)
  386. @return: the session attribute
  387. @rtype: L{Session} or L{None}
  388. """
  389. if self.isSecure():
  390. return self._secureSession
  391. else:
  392. return self._insecureSession
  393. def getSession(self, sessionInterface=None, forceNotSecure=False):
  394. """
  395. Check if there is a session cookie, and if not, create it.
  396. By default, the cookie with be secure for HTTPS requests and not secure
  397. for HTTP requests. If for some reason you need access to the insecure
  398. cookie from a secure request you can set C{forceNotSecure = True}.
  399. @param forceNotSecure: Should we retrieve a session that will be
  400. transmitted over HTTP, even if this L{Request} was delivered over
  401. HTTPS?
  402. @type forceNotSecure: L{bool}
  403. """
  404. # Make sure we aren't creating a secure session on a non-secure page
  405. secure = self.isSecure() and not forceNotSecure
  406. if not secure:
  407. cookieString = b"TWISTED_SESSION"
  408. sessionAttribute = "_insecureSession"
  409. else:
  410. cookieString = b"TWISTED_SECURE_SESSION"
  411. sessionAttribute = "_secureSession"
  412. session = getattr(self, sessionAttribute)
  413. if session is not None:
  414. # We have a previously created session.
  415. try:
  416. # Refresh the session, to keep it alive.
  417. session.touch()
  418. except (AlreadyCalled, AlreadyCancelled):
  419. # Session has already expired.
  420. session = None
  421. if session is None:
  422. # No session was created yet for this request.
  423. cookiename = b"_".join([cookieString] + self.sitepath)
  424. sessionCookie = self.getCookie(cookiename)
  425. if sessionCookie:
  426. try:
  427. session = self.site.getSession(sessionCookie)
  428. except KeyError:
  429. pass
  430. # if it still hasn't been set, fix it up.
  431. if not session:
  432. session = self.site.makeSession()
  433. self.addCookie(cookiename, session.uid, path=b"/", secure=secure)
  434. setattr(self, sessionAttribute, session)
  435. if sessionInterface:
  436. return session.getComponent(sessionInterface)
  437. return session
  438. def _prePathURL(self, prepath):
  439. port = self.getHost().port
  440. if self.isSecure():
  441. default = 443
  442. else:
  443. default = 80
  444. if port == default:
  445. hostport = ""
  446. else:
  447. hostport = ":%d" % port
  448. prefix = networkString(
  449. "http%s://%s%s/"
  450. % (
  451. self.isSecure() and "s" or "",
  452. nativeString(self.getRequestHostname()),
  453. hostport,
  454. )
  455. )
  456. path = b"/".join([quote(segment, safe=b"") for segment in prepath])
  457. return prefix + path
  458. def prePathURL(self):
  459. return self._prePathURL(self.prepath)
  460. def URLPath(self):
  461. from twisted.python import urlpath
  462. return urlpath.URLPath.fromRequest(self)
  463. def rememberRootURL(self):
  464. """
  465. Remember the currently-processed part of the URL for later
  466. recalling.
  467. """
  468. url = self._prePathURL(self.prepath[:-1])
  469. self.appRootURL = url
  470. def getRootURL(self):
  471. """
  472. Get a previously-remembered URL.
  473. @return: An absolute URL.
  474. @rtype: L{bytes}
  475. """
  476. return self.appRootURL
  477. def _handleStar(self):
  478. """
  479. Handle receiving a request whose path is '*'.
  480. RFC 7231 defines an OPTIONS * request as being something that a client
  481. can send as a low-effort way to probe server capabilities or readiness.
  482. Rather than bother the user with this, we simply fast-path it back to
  483. an empty 200 OK. Any non-OPTIONS verb gets a 405 Method Not Allowed
  484. telling the client they can only use OPTIONS.
  485. """
  486. if self.method == b"OPTIONS":
  487. self.setResponseCode(http.OK)
  488. else:
  489. self.setResponseCode(http.NOT_ALLOWED)
  490. self.setHeader(b"Allow", b"OPTIONS")
  491. # RFC 7231 says we MUST set content-length 0 when responding to this
  492. # with no body.
  493. self.setHeader(b"Content-Length", b"0")
  494. self.finish()
  495. @implementer(iweb._IRequestEncoderFactory)
  496. class GzipEncoderFactory:
  497. """
  498. @cvar compressLevel: The compression level used by the compressor, default
  499. to 9 (highest).
  500. @since: 12.3
  501. """
  502. _gzipCheckRegex = re.compile(rb"(:?^|[\s,])gzip(:?$|[\s,])")
  503. compressLevel = 9
  504. def encoderForRequest(self, request):
  505. """
  506. Check the headers if the client accepts gzip encoding, and encodes the
  507. request if so.
  508. """
  509. acceptHeaders = b",".join(
  510. request.requestHeaders.getRawHeaders(b"Accept-Encoding", [])
  511. )
  512. if self._gzipCheckRegex.search(acceptHeaders):
  513. encoding = request.responseHeaders.getRawHeaders(b"Content-Encoding")
  514. if encoding:
  515. encoding = b",".join(encoding + [b"gzip"])
  516. else:
  517. encoding = b"gzip"
  518. request.responseHeaders.setRawHeaders(b"Content-Encoding", [encoding])
  519. return _GzipEncoder(self.compressLevel, request)
  520. @implementer(iweb._IRequestEncoder)
  521. class _GzipEncoder:
  522. """
  523. An encoder which supports gzip.
  524. @ivar _zlibCompressor: The zlib compressor instance used to compress the
  525. stream.
  526. @ivar _request: A reference to the originating request.
  527. @since: 12.3
  528. """
  529. _zlibCompressor = None
  530. def __init__(self, compressLevel, request):
  531. self._zlibCompressor = zlib.compressobj(
  532. compressLevel, zlib.DEFLATED, 16 + zlib.MAX_WBITS
  533. )
  534. self._request = request
  535. def encode(self, data):
  536. """
  537. Write to the request, automatically compressing data on the fly.
  538. """
  539. if not self._request.startedWriting:
  540. # Remove the content-length header, we can't honor it
  541. # because we compress on the fly.
  542. self._request.responseHeaders.removeHeader(b"Content-Length")
  543. return self._zlibCompressor.compress(data)
  544. def finish(self):
  545. """
  546. Finish handling the request request, flushing any data from the zlib
  547. buffer.
  548. """
  549. remain = self._zlibCompressor.flush()
  550. self._zlibCompressor = None
  551. return remain
  552. class _RemoteProducerWrapper:
  553. def __init__(self, remote):
  554. self.resumeProducing = remote.remoteMethod("resumeProducing")
  555. self.pauseProducing = remote.remoteMethod("pauseProducing")
  556. self.stopProducing = remote.remoteMethod("stopProducing")
  557. class Session(components.Componentized):
  558. """
  559. A user's session with a system.
  560. This utility class contains no functionality, but is used to
  561. represent a session.
  562. @ivar site: The L{Site} that generated the session.
  563. @type site: L{Site}
  564. @ivar uid: A unique identifier for the session.
  565. @type uid: L{bytes}
  566. @ivar _reactor: An object providing L{IReactorTime} to use for scheduling
  567. expiration.
  568. @ivar sessionTimeout: Time after last modification the session will expire,
  569. in seconds.
  570. @type sessionTimeout: L{float}
  571. @ivar lastModified: Time the C{touch()} method was last called (or time the
  572. session was created). A UNIX timestamp as returned by
  573. L{IReactorTime.seconds()}.
  574. @type lastModified: L{float}
  575. """
  576. sessionTimeout = 900
  577. _expireCall = None
  578. def __init__(self, site, uid, reactor=None):
  579. """
  580. Initialize a session with a unique ID for that session.
  581. @param reactor: L{IReactorTime} used to schedule expiration of the
  582. session. If C{None}, the reactor associated with I{site} is used.
  583. """
  584. super().__init__()
  585. if reactor is None:
  586. reactor = site.reactor
  587. self._reactor = reactor
  588. self.site = site
  589. self.uid = uid
  590. self.expireCallbacks = []
  591. self.touch()
  592. self.sessionNamespaces = {}
  593. def startCheckingExpiration(self):
  594. """
  595. Start expiration tracking.
  596. @return: L{None}
  597. """
  598. self._expireCall = self._reactor.callLater(self.sessionTimeout, self.expire)
  599. def notifyOnExpire(self, callback):
  600. """
  601. Call this callback when the session expires or logs out.
  602. """
  603. self.expireCallbacks.append(callback)
  604. def expire(self):
  605. """
  606. Expire/logout of the session.
  607. """
  608. del self.site.sessions[self.uid]
  609. for c in self.expireCallbacks:
  610. c()
  611. self.expireCallbacks = []
  612. if self._expireCall and self._expireCall.active():
  613. self._expireCall.cancel()
  614. # Break reference cycle.
  615. self._expireCall = None
  616. def touch(self):
  617. """
  618. Mark the session as modified, which resets expiration timer.
  619. """
  620. self.lastModified = self._reactor.seconds()
  621. if self._expireCall is not None:
  622. self._expireCall.reset(self.sessionTimeout)
  623. version = networkString(f"TwistedWeb/{copyright.version}")
  624. @implementer(interfaces.IProtocolNegotiationFactory)
  625. class Site(HTTPFactory):
  626. """
  627. A web site: manage log, sessions, and resources.
  628. @ivar requestFactory: A factory which is called with (channel)
  629. and creates L{Request} instances. Default to L{Request}.
  630. @ivar displayTracebacks: If set, unhandled exceptions raised during
  631. rendering are returned to the client as HTML. Default to C{False}.
  632. @ivar sessionFactory: factory for sessions objects. Default to L{Session}.
  633. @ivar sessions: Mapping of session IDs to objects returned by
  634. C{sessionFactory}.
  635. @type sessions: L{dict} mapping L{bytes} to L{Session} given the default
  636. C{sessionFactory}
  637. @ivar counter: The number of sessions that have been generated.
  638. @type counter: L{int}
  639. @ivar sessionCheckTime: Deprecated and unused. See
  640. L{Session.sessionTimeout} instead.
  641. """
  642. counter = 0
  643. requestFactory = Request
  644. displayTracebacks = False
  645. sessionFactory = Session
  646. sessionCheckTime = 1800
  647. _entropy = os.urandom
  648. def __init__(self, resource, requestFactory=None, *args, **kwargs):
  649. """
  650. @param resource: The root of the resource hierarchy. All request
  651. traversal for requests received by this factory will begin at this
  652. resource.
  653. @type resource: L{IResource} provider
  654. @param requestFactory: Overwrite for default requestFactory.
  655. @type requestFactory: C{callable} or C{class}.
  656. @see: L{twisted.web.http.HTTPFactory.__init__}
  657. """
  658. super().__init__(*args, **kwargs)
  659. self.sessions = {}
  660. self.resource = resource
  661. if requestFactory is not None:
  662. self.requestFactory = requestFactory
  663. def _openLogFile(self, path):
  664. from twisted.python import logfile
  665. return logfile.LogFile(os.path.basename(path), os.path.dirname(path))
  666. def __getstate__(self):
  667. d = self.__dict__.copy()
  668. d["sessions"] = {}
  669. return d
  670. def _mkuid(self):
  671. """
  672. (internal) Generate an opaque, unique ID for a user's session.
  673. """
  674. self.counter = self.counter + 1
  675. return hexlify(self._entropy(32))
  676. def makeSession(self):
  677. """
  678. Generate a new Session instance, and store it for future reference.
  679. """
  680. uid = self._mkuid()
  681. session = self.sessions[uid] = self.sessionFactory(self, uid)
  682. session.startCheckingExpiration()
  683. return session
  684. def getSession(self, uid):
  685. """
  686. Get a previously generated session.
  687. @param uid: Unique ID of the session.
  688. @type uid: L{bytes}.
  689. @raise KeyError: If the session is not found.
  690. """
  691. return self.sessions[uid]
  692. def buildProtocol(self, addr):
  693. """
  694. Generate a channel attached to this site.
  695. """
  696. channel = super().buildProtocol(addr)
  697. channel.requestFactory = self.requestFactory
  698. channel.site = self
  699. return channel
  700. isLeaf = 0
  701. def render(self, request):
  702. """
  703. Redirect because a Site is always a directory.
  704. """
  705. request.redirect(request.prePathURL() + b"/")
  706. request.finish()
  707. def getChildWithDefault(self, pathEl, request):
  708. """
  709. Emulate a resource's getChild method.
  710. """
  711. request.site = self
  712. return self.resource.getChildWithDefault(pathEl, request)
  713. def getResourceFor(self, request):
  714. """
  715. Get a resource for a request.
  716. This iterates through the resource hierarchy, calling
  717. getChildWithDefault on each resource it finds for a path element,
  718. stopping when it hits an element where isLeaf is true.
  719. """
  720. request.site = self
  721. # Sitepath is used to determine cookie names between distributed
  722. # servers and disconnected sites.
  723. request.sitepath = copy.copy(request.prepath)
  724. return resource.getChildForRequest(self.resource, request)
  725. # IProtocolNegotiationFactory
  726. def acceptableProtocols(self):
  727. """
  728. Protocols this server can speak.
  729. """
  730. baseProtocols = [b"http/1.1"]
  731. if http.H2_ENABLED:
  732. baseProtocols.insert(0, b"h2")
  733. return baseProtocols