server.py 28 KB

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