Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

server.py 29KB

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