vhost.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. # -*- test-case-name: twisted.web.
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. I am a virtual hosts implementation.
  6. """
  7. # Twisted Imports
  8. from twisted.python import roots
  9. from twisted.web import pages, resource
  10. class VirtualHostCollection(roots.Homogenous):
  11. """Wrapper for virtual hosts collection.
  12. This exists for configuration purposes.
  13. """
  14. entityType = resource.Resource
  15. def __init__(self, nvh):
  16. self.nvh = nvh
  17. def listStaticEntities(self):
  18. return self.nvh.hosts.items()
  19. def getStaticEntity(self, name):
  20. return self.nvh.hosts.get(self)
  21. def reallyPutEntity(self, name, entity):
  22. self.nvh.addHost(name, entity)
  23. def delEntity(self, name):
  24. self.nvh.removeHost(name)
  25. class NameVirtualHost(resource.Resource):
  26. """I am a resource which represents named virtual hosts."""
  27. default = None
  28. def __init__(self):
  29. """Initialize."""
  30. resource.Resource.__init__(self)
  31. self.hosts = {}
  32. def listStaticEntities(self):
  33. return resource.Resource.listStaticEntities(self) + [
  34. ("Virtual Hosts", VirtualHostCollection(self))
  35. ]
  36. def getStaticEntity(self, name):
  37. if name == "Virtual Hosts":
  38. return VirtualHostCollection(self)
  39. else:
  40. return resource.Resource.getStaticEntity(self, name)
  41. def addHost(self, name, resrc):
  42. """Add a host to this virtual host.
  43. This will take a host named `name', and map it to a resource
  44. `resrc'. For example, a setup for our virtual hosts would be::
  45. nvh.addHost('divunal.com', divunalDirectory)
  46. nvh.addHost('www.divunal.com', divunalDirectory)
  47. nvh.addHost('twistedmatrix.com', twistedMatrixDirectory)
  48. nvh.addHost('www.twistedmatrix.com', twistedMatrixDirectory)
  49. """
  50. self.hosts[name] = resrc
  51. def removeHost(self, name):
  52. """Remove a host."""
  53. del self.hosts[name]
  54. def _getResourceForRequest(self, request):
  55. """(Internal) Get the appropriate resource for the given host."""
  56. hostHeader = request.getHeader(b"host")
  57. if hostHeader is None:
  58. return self.default or pages.notFound()
  59. else:
  60. host = hostHeader.lower().split(b":", 1)[0]
  61. return self.hosts.get(host, self.default) or pages.notFound(
  62. "Not Found",
  63. f"host {host.decode('ascii', 'replace')!r} not in vhost map",
  64. )
  65. def render(self, request):
  66. """Implementation of resource.Resource's render method."""
  67. resrc = self._getResourceForRequest(request)
  68. return resrc.render(request)
  69. def getChild(self, path, request):
  70. """Implementation of resource.Resource's getChild method."""
  71. resrc = self._getResourceForRequest(request)
  72. if resrc.isLeaf:
  73. request.postpath.insert(0, request.prepath.pop(-1))
  74. return resrc
  75. else:
  76. return resrc.getChildWithDefault(path, request)
  77. class _HostResource(resource.Resource):
  78. def getChild(self, path, request):
  79. if b":" in path:
  80. host, port = path.split(b":", 1)
  81. port = int(port)
  82. else:
  83. host, port = path, 80
  84. request.setHost(host, port)
  85. prefixLen = 3 + request.isSecure() + 4 + len(path) + len(request.prepath[-3])
  86. request.path = b"/" + b"/".join(request.postpath)
  87. request.uri = request.uri[prefixLen:]
  88. del request.prepath[:3]
  89. return request.site.getResourceFor(request)
  90. class VHostMonsterResource(resource.Resource):
  91. """
  92. Use this to be able to record the hostname and method (http vs. https)
  93. in the URL without disturbing your web site. If you put this resource
  94. in a URL http://foo.com/bar then requests to
  95. http://foo.com/bar/http/baz.com/something will be equivalent to
  96. http://foo.com/something, except that the hostname the request will
  97. appear to be accessing will be "baz.com". So if "baz.com" is redirecting
  98. all requests for to foo.com, while foo.com is inaccessible from the outside,
  99. then redirect and url generation will work correctly
  100. """
  101. def getChild(self, path, request):
  102. if path == b"http":
  103. request.isSecure = lambda: 0
  104. elif path == b"https":
  105. request.isSecure = lambda: 1
  106. return _HostResource()